【问题标题】:React.js - TypeError: Cannot read property 'catch' of undefinedReact.js - TypeError:无法读取未定义的属性'catch'
【发布时间】:2018-02-27 19:34:35
【问题描述】:

组件 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: Cannot read property 'catch' of undefined

组件登录页面

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);

操作/身份验证

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)));

你能解释一下为什么 undefined catch 吗?函数使用 promise then() 提交返回结果。

【问题讨论】:

  • 您正在返回 .then,这是 .login 函数的结果
  • 显然是因为this.props.submit 没有返回任何东西
  • submit = data =&gt; { this.props.login(data).then(() =&gt; this.props.history.push("/")); } 更改为submit = data =&gt; this.props.login(data).then(() =&gt; this.props.history.push("/"));submit = data =&gt; { return this.props.login(data).then(() =&gt; this.props.history.push("/")); }
  • @Sag1v 不,没有任何返回
  • 阅读 arrow documentation 以了解拥有 {} 和没有 {} 之间的区别 - 即 "concise body"

标签: javascript reactjs promise


【解决方案1】:

您应该将catch 移动到LoginPage

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

如果需要,将错误作为道具传递给LoginForm

【讨论】:

    【解决方案2】:

    删除承诺处的 {}。 应该是这样的

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

    【讨论】:

      猜你喜欢
      • 2022-01-16
      • 2021-11-08
      • 2022-12-05
      • 2021-10-24
      • 2019-12-20
      • 2021-04-12
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多