我有一个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等中创建任何东西。
答案 0 :(得分:4)
解决方案很简单。我只需要在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);
})