我是React/Redux的新手,所以我使用Redux Form构建了一个简单的博客应用程序来帮助我学习。现在我不清楚在我的操作中从表单向api提交数据时如何处理ajax错误。主要问题是我使用Redux Form的onSubmitSuccess配置属性,并且它似乎总是被调用,即使发生错误。我真的不清楚什么触发onSubmitSuccess或onSubmitFail。我的onSubmitFail函数永远不会执行,但我的onSubmitSuccess函数始终是,无论是否发生错误。使用Redux表单处理AJAX错误
我的终极版形式的文档阅读SubmissionError,但它说,它的目的是“从承诺拒绝,因为AJAX I/O区分承诺拒绝,因为验证错误的”。所以,这听起来像是我需要的相反。
我使用REDX-promise作为中间件与Redux,如果这有什么区别。
这是我的代码。我故意扔在我的服务器API误差来产生在我createPost动作错误:
集装箱用我的终极版形式
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?
}
}
这很好。出于某种原因,我认为像ajax调用这样的事情只能在你的行为中处理。我没有考虑在我的onSubmit函数中做这件事。 – Adam