[英]How to wait for redux thunk to dispatch action
由於redux thunk異步調用動作創建者返回的函數,在調用動作創建者之后我如何確保redux在繼續之前實際調度了動作?
我需要在每個POST請求到服務器之前獲取CSRF令牌,並且對於這兩個過程都有相應的操作。
問題是,如果我連續調用這些動作創建者,POST動作由於某種原因在調度CSRF動作之前被調度。 我想將這些問題分開,所以我不想將這些行為結合起來。
我如何同步動作創建者調用代碼與redux thunk調度這些動作?
您可以將thunk action creator設為Promise,以便更輕松地控制異步作業。
export function createXHRAction(xhrType, dispatch, options) {
// you can customize createXHRAction here with options parameter.
dispatch({ type: xhrType, data: { fetching: true, data: [] });
return new Promise( (resolve, reject) => {
fetch(options.url, { ... })
.then( (response) => {
// to getting server response, you must use .json() method and this is promise object
let parseJSONPromise = response.json();
if(response.status >= 200 && response.status < 300) {
parseJSONPromise.then( (result) => {
dispatch({ type: xhrType, data: { fetching: false, data: result.data });
resolve(result.data);
});
return parseJSONPromise; // make possible to use then where calling this
}
else {
return parseJSONPromise.then( res => {
reject({ message: res.error.message });
});
}
})
.catch( (error) => {
// handles common XHR error here
});
});
}
現在您可以輕松地創建新的XHR操作,如下所示:
import { createXHRAction } from './actions';
export function getUser(id) {
return (dispatch) => {
return createXHRAction('user', dispatch, {
method: 'get',
url: `/user/${id}`
});
};
}
現在你可以像同步一樣使用thunk動作:
import { dispatch } from './store';
import { getUser } from './action/user';
class SomeComponent extends React.Component {
...
loadData(id) {
// from here, store's state should be { fetching: true, data: [] }
dispatch(getUser(id))
.then( (userData) => {
// now from here, you can get the value from parameter or you can get it from store or component props if super component passing it by redux provider.
// store state should be { fetching: false: data [..., ...] }
// do something with received data
})
.catch( (error) => {
}));
}
}
在啟動POST請求之前,您需要等待CSRF令牌請求完成。
我認為將所有代碼包裝成動作創建者會更好
function postAction(data) {
fetchToken().then((token) => {
//you have got token here and can use it for the POST-request.
doPost(data, token).then(() => {
//dispatch success action if you need so
})
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.