我不明白为什么需要像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的实现,以及它如何改进类似于上面的示例的现有解决方案。
发布于 2017-05-05 00:41:30
Redux Thunk教Redux识别实际上是函数的特殊类型的动作。
当动作创建者返回一个函数时,该函数将由Redux Thunk中间件执行。此函数不需要是纯函数;因此允许它产生副作用,包括执行异步API调用。该函数还可以分派操作。
thunk可用于延迟操作的调度,或者仅在满足特定条件时才调度。
如果启用了Redux Thunk中间件,则每当您尝试分派函数而不是操作对象时,中间件都会使用分派方法本身作为第一个参数来调用该函数。
然后,由于我们“教”Redux识别这样的“特殊”动作创建者(我们称他们为thunk动作创建者),我们现在可以在任何我们将使用常规动作创建者的地方使用它们。
请查看丹·阿布拉莫夫本人的答案,它涵盖了所有内容:https://stackoverflow.com/a/35415559/5714933
另请查看以下链接以了解更多信息:
https://github.com/gaearon/redux-thunk#motivation http://redux.js.org/docs/advanced/AsyncActions.html
https://stackoverflow.com/questions/43788447
复制相似问题