2 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
直接來自redux-thunk自述文件:
function makeASandwichWithSecretSauce(forPerson) {
// We can invert control here by returning a function - the "thunk".
// When this function is passed to `dispatch`, the thunk middleware will intercept it,
// and call it with `dispatch` and `getState` as arguments.
// This gives the thunk function the ability to run some logic, and still interact with the store.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
...
// It even takes care to return the thunk’s return value
// from the dispatch, so I can chain Promises as long as I return them.
store.dispatch(
makeASandwichWithSecretSauce('My partner')
).then(() => {
console.log('Done!');
});

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
當(dāng)您想從外部源(例如REST)中獲取某些數(shù)據(jù)時(shí),會(huì)使用Promise。但是,如果您確實(shí)要執(zhí)行此操作,則動(dòng)作創(chuàng)建者必須返回一個(gè)函數(shù):
export const updateActivePage = (activePage) => {
return (dispatch) => {
return dispatch ({
type: UPDATE_ACTIVEPAGE,
payload: activePage
});
}
}
這樣的事情應(yīng)該返回承諾。但是,將在分派操作時(shí)解決此承諾。它與redux狀態(tài)更改不同。我認(rèn)為您真的不想在這里使用promise。
如果要在redux狀態(tài)發(fā)生變化時(shí)做出反應(yīng),則組件應(yīng)觀察狀態(tài)(使用mapStateToProps),并且可以處理componentWillUpdate方法中的更改。
添加回答
舉報(bào)