首页 文章

redux-form:在服务器验证错误后抛出SubmissionError

提问于
浏览
2

我一直在尝试使用redux-form(v6.5.0)进行提交验证,并在登录时出现服务器验证错误后抛出SubmissionError .

在这里的示例Submit Validation Example中,submit函数使用promise并在回调错误上抛出SubmissionError,如果我遵循此工作流程,这对我来说很好 . 但在我的情况下,我想在提交表单上发送登录操作,并使用reducer来更改商店中的状态 .

这是我正在尝试做的一个基本示例:

LoginForm.js

const LoginForm = ({handleSubmit, submitting, error,}) => {
  ...
  return (
    <form onSubmit={handleSubmit}>
      <div>
        <Field name="email" component="input" type="email" component={renderField} label="Email" validate={email}/>
      </div>
      <div>
        <Field name="password" component="input" type="password" component={renderField} label="Password" validate={required}/>
      </div>
      <button type="submit" disabled={submitting}>Log In</button>
    </form>
  )
}

export default reduxForm({
  form: 'loginForm'
})(LoginForm)

LoginPage.js

class LoginPage extends Component {

  handleSubmit = (values) => {
    this.props.dispatch(login(values));
  }

  render() {
    return (
      <div>
        {this.props.fetching && <p>LOGGING IN...</p>}
        <LoginForm onSubmit={this.handleSubmit} />
      </div>
    );
  }
}

如您所见, handleSubmit 仅调度登录操作,并且不知道将发生的服务器错误 .

Login action 看起来像这样:

function login({ email, password }) {
  return function(dispatch) {
    dispatch({type: "LOGIN_USER_PENDING"})
    setTimeout(() => {
      dispatch({type: "LOGIN_USER_REJECTED", payload: "Invalid username or password"})
    }, 2000);
  }
}

Reducer 看起来像这样:

case "LOGIN_USER_PENDING":
  return {...state, fetching: true}
case "LOGIN_USER_REJECTED":
  return {...state, fetching: false, error: action.payload}

我可以成功识别LoginPage中的错误,但我不能在handleSubmit函数之外抛出SubmissionError .

Questions:

  • 有没有办法从组件生命周期中的另一个函数抛出此SubmissionError?

  • 如果没有,如何实现?我是否通过从提交中发送登录操作而不是使用来自此处的承诺来做错了?

谢谢 .

2 回答

  • 0

    你需要检查asyncValidation example . 您需要将 asyncValidate 添加到表单配置中,您将能够从自定义 asyncValidate 函数中抛出错误 .

  • 0

    我找到了一个解决方案,但我没有使用SubmissionError机制来完成这项工作并为我显示错误 . 所以仍然可能有一个更清洁的解决方案 .

    由于我在状态更改时在LoginPage组件中收到错误,我只需将其转发到LoginForm并手动显示 .

    LoginPage.js

    class LoginPage extends Component {
      render() {
        return (
          <div>
            {this.props.fetching && <p>LOGGING IN...</p>}
            <LoginForm onSubmit={this.handleSubmit} _error={this.props.error} />
          </div>
        );
      }
    }
    

    LoginForm.js

    const LoginForm = ({handleSubmit, submitting, _error,}) => {
      ...
      return (
        <form onSubmit={handleSubmit}>
          {_error && <strong>{_error}</strong>}
          <div>
            ...
          </div>
          <button type="submit" disabled={submitting}>Log In</button>
        </form>
      )
    }
    

    我很高兴听到任何可以改善解决方案的建议 .

相关问题