2017-10-13 105 views
0

我是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? 
    } 
} 

回答

1

在你的情况下,redux-form不知道表单提交是否成功,因为你没有从onSubmit函数返回一个Promise。

在你的情况下,有可能实现这一目标,而无需使用redux-promise或任何其他异步处理库:

PostsNew = reduxForm({ 
    validate, 
    form: 'PostsNewForm', 
    onSubmit(values, dispatch, props) { 
    // as axios returns a Promise, we are good here 
    return axios.post('/api/posts', values); 
    } 
    onSubmitSuccess(result, dispatch, props) { 
    // if request was succeeded(axios will resolve Promise), that function will be called 
    // and we can dispatch success action 
    dispatch({ 
     type: CREATE_POST, 
     payload: response 
    }) 
    }, 
    onSubmitFail(errors, dispatch) { 
    // if request was failed(axios will reject Promise), we will reach that function 
    // and could dispatch failure action 
    dispatch({ 
     type: CREATE_POST_FAILURE, 
     payload: errors 
    }) 
    } 
})(PostsNew) 
+0

这很好。出于某种原因,我认为像ajax调用这样的事情只能在你的行为中处理。我没有考虑在我的onSubmit函数中做这件事。 – Adam

1
称为

对于处理异步操作,您应该使用redux-thunkredux-saga或其他中间件,这样可以运行异步代码。

+0

我知道,使用中间件是处理异步操作的最佳方法。我不知道你是否注意到我说我在我的问题中使用了redux-promise中间件?我可以使用redux-thunk,但是我的问题是我不知道在使用这个中间件时如何处理错误。我不知道什么会取消我已经用redux-form配置的onSubmitSuccess函数,或者什么会触发onSubmitFail。问题是关于如何专门用redux-form来处理错误。 – Adam