React.js - TypeError:无法读取未定义的属性'catch'

时间:2017-09-19 06:22:58

标签: javascript reactjs promise

组件LoginForm有以下代码:

class LoginForm extends React.Component {
  .................................................................
    onSubmit = (e) => {
      e.preventDefault();
      const errors = this.validate(this.state.data);
      this.setState({ loading: true});
      this.props.submit(this.state.data).catch(console.log("errors"));

    }

    .....................................................................   
}

LoginForm.PropTypes = {
  submit: PropTypes.func.isRequired
};

export default LoginForm;

当我提交按钮时,我收到错误 TypeError:无法读取未定义的属性'catch'

组件登录页

class LoginPage extends React.Component {
  submit = data => {
    this.props.login(data).then(() => this.props.history.push("/"));
  }

  render() {
    return(
      <div className="login-page">
        <main>
          <div className="login-block">
            <img src="assets/img/logo.png" alt=""/>
            <h1>Log into your account</h1>
            <LoginForm submit={this.submit} />
          </div>
          <div className="login-links">
            <a className="pull-left" href="user-forget-pass.html">Forget Password?</a>
            <a className="pull-right" href="user-register.html">Register an account</a>
          </div>
        </main>
      </div>
    );
  }
}

LoginPage.propTypes = {
  history: PropTypes.shape({
    push: PropTypes.func.isRequired
  }).isRequired,
  login: PropTypes.func.isRequired
};

export default connect(null, {login})(LoginPage);

操作/ AUTH

import { USER_LOGGED_IN } from "../types";
import api from "../api";

export const userLoggedIn = user => ({
  type: USER_LOGGED_IN,
  user    
});

export const login = credentials => dispatch =>
  api.user.login(credentials)
    .then(user => dispatch(userLoggedIn(user)));

你能解释为什么未定义捕获?函数提交返回结果与promise然后()。

2 个答案:

答案 0 :(得分:0)

您应将catch移至LoginPage

submit = data => {
  this.props.login(data)
    .then(() => this.props.history.push("/"))
    .catch(console.log)
}

如有必要,将错误作为道具传递给LoginForm

答案 1 :(得分:0)

删除诺言中的{}。 应该是这样

submit = data => this.props.login(data).then(() => this.props.history.push("/"));