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