[英]throwing redux-form submissions errors from handleSubmit functions
我有一个redux-form,它有一个handleSubmit函数,我用它来做一些异步的http服务器验证。 如果由于某种原因身份验证失败,我想抛出一个redux-form错误。 如果我抛出“SubmissionError”,我会收到一条错误消息: Uncaught (in promise)
我的代码:
class MyLoginForm extends Component { handleSubmit({ email, password }) { axios.post("http://API_SERVER/login", null, { withCredentials: true, auth: { username: email, password: password } }) .then((response) => { console.log('HTTP call success. JWT Token is:', response.data); }) .catch(err => { console.log(err) >>>> WHAT TO DO TO CONVEY THE ERROR IN THE REDUX-FORM <<<< if (err.response) { if (err.response.status !== 200) { console.log("Unexpected error code from the API server", err.response.status); throw new SubmissionError({ _error: 'HTTP Error. Possibly invalid username / password' }); } return } throw new SubmissionError({ _error: 'HTTP Error. Please contact Helpdesk' }); }); } render() { const { error, handleSubmit, pristine, reset, submitting } = this.props return ( <form onSubmit={handleSubmit(this.handleSubmit.bind(this))}> <Field name="email" type="email" component={renderField} label="Email Address" /> <Field name="password" type="password" component={renderField} label="Password" /> {error && <strong>{error}</strong>} <div> <button type="submit" disabled={submitting}>Log In</button> <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button> </div> </form> ) } } export default connect(null, actions)(reduxForm({ form: 'MyLoginForm' // a unique identifier for this form })(MyLoginForm));
我想要一个解决方案来更新/呈现redux-form本身的错误消息,而不在全局状态,reducers等中创建任何东西。
解决方案很简单。 我只需要在axios电话前添加一个return
。 所以更新的代码将是:
handleSubmit({ email, password }) {
return axios.post("http://API_SERVER/login", null, { withCredentials: true, auth: { username: email, password: password } })
.then((response) => {
console.log('HTTP call success. JWT Token is:', response.data);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.