为什么在handleLogin方法中未定义this.props?

时间:2019-04-29 07:46:13

标签: reactjs redux

我有一个带有redux表单的Login组件。单击登录按钮后,将调用handleLogin方法。表单中的数据也很好地传递了。但是当我在方法内部调用this.props时,它显示的是未定义的道具。

class Login extends Component {
  static propTypes = {
    signInUser: PropTypes.func
  };

  gotoSignUp = () => {
    this.props.history.push("/signup");
  };

  handleLogin(values) {
    const data = values.toJS();
    this.props.signInUser(data);
  }

  render() {
    const { handleSubmit } = this.props;

    return (
      <div className="container card bg-dark medium-form mt-5 pb-3">
        <div className="row">
          <div className="col">
            <form onSubmit={handleSubmit(this.handleLogin)}>
              <FormInput
                name="email"
                label="Email"
                placeholder="Enter email"
                type="email"
                icon="fa fa-envelope"
              />
              <FormInput
                name="password"
                label="Password"
                placeholder="Enter password"
                type="password"
                icon="fa fa-key"
              />
              <div className="row">
                <div className="col-md-2" />
                <div className="col">
                  <button
                    type="submit"
                    className="btn btn-outline-light btn-md"
                    style={{ float: "right" }}
                  >
                    <i className="fa fa-sign-in" />
                    &nbsp;Login
                  </button>
                </div>
                <div className="col">
                  <button
                    type="button"
                    className="btn btn-outline-light btn-md"
                    onClick={this.gotoSignUp}
                  >
                    <i className="fa fa-user-plus" />
                    &nbsp;Sign up
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

Login = reduxForm({
  form: "login",
  validate
})(Login);

const mapDispatchToProps = dispatch => ({
  signInUser: data => dispatch(loginUser(data))
});

const withConnect = connect(
  null,
  mapDispatchToProps
);

export default compose(withConnect)(Login);

我还有另一个组件,例如相同的命名寄存器。寄存器组件也是如此,没有任何错误。

2 个答案:

答案 0 :(得分:2)

如果需要this.props可用,则需要将其绑定到构造函数或继续使用语法行,并将handleLogin转换为arrow函数。

handleLogin = (values) => {
    const data = values.toJS();
    this.props.signInUser(data);
  }

答案 1 :(得分:0)

将handleLogin()函数转换为箭头函数,如下所示:

handleLogin = (values) => { ... }