2017-10-13 108 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