首页 > 解决方案 > Login.js:6 Uncaught TypeError: Cannot read property 'then' of undefined

问题描述

登录成功后,我试图重定向到仪表板,但它不起作用。我收到类似这样的错误。

未捕获的类型错误:无法读取未定义的属性“then”

这是我的代码

登录.js

import {connect} from 'react-redux';
 import LoginForm from "../Form/LoginForm";
 import {userLoggedIn} from '../../redux/actions/auth';
class Login extends Component {
    submit = data => this.props.userLoggedIn(data).then(()=> this.props.history.push("/dashboard"));
    render() {
       console.log(this.props)     <!---here when i try to log see image for result---->
        return (
            <div>
           <LoginForm submit={this.submit}/>
            </div>
        );
    }
}

export default connect(null, {userLoggedIn})(Login);

控制台.log(this.props); 登录日志图像

redux/action/auth.js

export const userLoggedIn = (user)=> dispatch => {
    axios.post('/api/login', {user})
        .then(res => {
            localStorage.redditToken = res.data.user.token;
            setAuthorizationHeader(res.data.user.token);
            dispatch({
                type: USER_LOGGED_IN,
                payload: res
            })
        })
        .catch()
};

标签: javascriptreactjsreact-redux

解决方案


您没有返回这axios call就是为什么它显示为空。正如上面评论中所说,一个承诺应该恢复then工作。只需返回axios.post.

export const userLoggedIn = (user) => dispatch => {
  return axios.post('/api/login', {
      user
    })
    .then(res => {
      localStorage.redditToken = res.data.user.token;
      setAuthorizationHeader(res.data.user.token);
      dispatch({
        type: USER_LOGGED_IN,
        payload: res
      })
    })
    .catch()
};

推荐阅读