<分区>
我不明白需要像 redux-thunk
这样的东西。据我了解,thunk
是一个返回函数的函数。在我看来,包装表达式和中间件的使用更能混淆正在发生的事情。取自redux-thunk
的示例代码
import thunk from 'redux-thunk';
// Note: this API requires redux@>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
// Meet thunks.
// A thunk is a function t hat returns a function.
// This is a thunk.
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
// Thunk middleware lets me dispatch thunk async actions
// as if they were actions!
store.dispatch(
makeASandwichWithSecretSauce('Me')
);
上面的代码可以写得更加简洁和直观:
fetchSecretSauce().then(
sauce => store.dispatch(makeASandwich('Me', sauce)),
error => store.dispatch(apologize('The Sandwich Shop', forPerson, error))
)
我的问题是 redux-thunk
满足什么需求,它如何改进与上述示例类似的现有解决方案。