【问题标题】:Redux form submit validation with redux thunkRedux 表单提交验证与 redux thunk
【发布时间】:2019-10-16 20:06:11
【问题描述】:

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

有什么帮助吗?

提交.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,
});

【问题讨论】:

  • 既然您使用的是 redux 表单,为什么不将验证器用作异步模糊验证器?或者您是否有任何特殊原因要在提交时验证电子邮件?更多关于异步模糊验证的信息 - redux-form.com/8.2.2/examples/asyncvalidation

标签: reactjs redux redux-form redux-thunk


【解决方案1】:
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()

【讨论】:

  • 当提交函数之外的 SubmissionError 给出错误时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 2017-05-09
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
相关资源
最近更新 更多