2 回答
TA贡献1860条经验 获得超8个赞
直接来自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贡献1786条经验 获得超11个赞
当您想从外部源(例如REST)中获取某些数据时,会使用Promise。但是,如果您确实要执行此操作,则动作创建者必须返回一个函数:
export const updateActivePage = (activePage) => {
return (dispatch) => {
return dispatch ({
type: UPDATE_ACTIVEPAGE,
payload: activePage
});
}
}
这样的事情应该返回承诺。但是,将在分派操作时解决此承诺。它与redux状态更改不同。我认为您真的不想在这里使用promise。
如果要在redux状态发生变化时做出反应,则组件应观察状态(使用mapStateToProps),并且可以处理componentWillUpdate方法中的更改。
添加回答
举报