Redux表单使用Redux Thunk提交验证

时间:2019-05-31 07:27:14

标签: reactjs redux redux-form redux-thunk

在我的表单中,我试图通过使用react-thunk来检查电子邮件,以确定是否已收到该电子邮件地址。除了一件事,一切都正常工作。我请求api,并将数据发送到reducer,但是我可以访问该状态的组件为空。因为组件中的状态值在减速器之前起作用。

有什么帮助吗?

Submit.js

onSubmit = data => {
    const { saveUser, validateEmail, emailValidate } = this.props;
    validateEmail(data.email); // action create for api request
    console.log(emailValidate); // fetch data in reducer(This data is empty because code run before reducer set state)
    if (emailValidate.statusMessage === 'OK') {
      throw new SubmissionError({ email: 'Email already in use', _error: 'Login failed!' });
    } else {

    }
  }

const mapDispatchToProps = (dispatch) => {
    validateEmail(email) {
      dispatch(validateEmail(email));
    },
  };
};
const mapStateToProps = (state) => ({
  emailValidate: state.registrationFormEmailValidate.data,
});

1 个答案:

答案 0 :(得分:0)

onSubmit = data => {
  const { saveUser, validateEmail, emailValidate } = this.props;
  validateEmail(data.email); // action create for api request
}

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.emailValidate.statusMessage !== prevProps.emailValidate.statusMessage) {
    console.log(this.props.emailValidate);
    if (this.props.emailValidate.statusMessage === 'OK') {
      throw new SubmissionError({ email: 'Email already in use', _error: 'Login failed!' });
    } else {

    }
  }
}

如果您使用的是class component,则可以使用componentDidUpdate()