【发布时间】:2017-07-23 08:26:17
【问题描述】:
我有一个 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 等中创建任何内容。
【问题讨论】:
-
只是检查一下,因为我在上面的代码中看不到 - 你添加了
import { SubmissionError } from 'redux-form',对吧? -
是的,我有。因此没有语法错误。
-
你可以试试@ptim 在回答这个问题stackoverflow.com/questions/34142678/… 中所做的事情。将您的 api 调用包装在 Promise 中,并在您的 catch 中使用拒绝回调。由于 promise 被拒绝,redux 表单将显示错误,如此处所述redux-form.com/6.0.0-rc.1/examples/submitValidation
-
axios 已经做到了。它使 http 调用响应处理一个承诺 iiuc
-
Vaibhav:你给我指出了正确的方向。我只需要把 axios 变成一个承诺。如果您可以添加解决方案,我很乐意接受它作为答案。还是我自己加一个?我已经让它工作了。谢谢。
标签: javascript reactjs redux redux-form