【发布时间】:2018-03-25 04:03:11
【问题描述】:
我是 React/Redux 的新手,所以我正在使用 Redux Form 构建一个简单的博客应用程序来帮助我学习。现在,我不清楚在我的操作中将数据从表单提交到 api 时如何处理 ajax 错误。主要问题是我正在使用 Redux Form 的 onSubmitSuccess 配置属性,它似乎总是被调用,即使发生错误也是如此。我真的不清楚是什么触发了 onSubmitSuccess 或 onSubmitFail。我的 onSubmitFail 函数永远不会执行,但我的 onSubmitSuccess 函数总是会执行,无论是否发生错误。
我在 redux-form 文档中读到了 SubmissionError,但它说它的目的是“区分由于验证错误而导致的承诺拒绝和由于 AJAX I/O 而导致的承诺拒绝”。所以,这听起来与我需要的相反。
如果这有什么不同的话,我会使用 redux-promise 作为 Redux 的中间件。
这是我的代码。我故意在我的服务器 api 中抛出一个错误以在我的 createPost 操作中生成错误:
带有我的 redux 表单的容器
PostsNew = reduxForm({
validate,
form: 'PostsNewForm',
onSubmit(values, dispatch, props) {
// calling my createPost action when the form is submitted.
// should I catch the error here?
// if so, what would I do to stop onSubmitSuccess from executing?
props.createPost(values)
}
onSubmitSuccess(result, dispatch, props) {
// this is always called, even when an exeption occurs in createPost()
},
onSubmitFail(errors, dispatch) {
// this function is never called
}
})(PostsNew)
onSubmit 调用的操作
export async function createPost(values) {
try {
const response = await axios.post('/api/posts', values)
return {
type: CREATE_POST,
payload: response
}
} catch (err) {
// what would I do here that would trigger onSubmitFail(),
// or stop onSubmitSuccess() from executing?
}
}
【问题讨论】:
标签: reactjs redux redux-form