mic*_*blu 21 javascript typescript reactjs redux-thunk react-redux
我不明白需要什么redux-thunk.据我所知,a 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')
);
Run Code Online (Sandbox Code Playgroud)
上面的代码可以写得更简洁直观:
fetchSecretSauce().then(
sauce => store.dispatch(makeASandwich('Me', sauce)),
error => store.dispatch(apologize('The Sandwich Shop', forPerson, error))
)
Run Code Online (Sandbox Code Playgroud)
我的问题是需要redux-thunk满足什么,以及它如何改进现有的解决方案,类似于上面的例子.
Moe*_*Moe 15
Redux Thunk教Redux识别实际上功能的特殊动作.
当动作创建者返回一个函数时,该函数将由Redux Thunk中间件执行.这个功能不需要是纯粹的; 因此允许它具有副作用,包括执行异步API调用.该功能还可以发送动作.
thunk可用于延迟动作的发送,或仅在满足某个条件时发送.
如果启用了Redux Thunk中间件,则只要您尝试调度函数而不是操作对象,中间件就会使用调度方法本身作为第一个参数来调用该函数.
然后,因为我们"教"Redux识别这样的"特殊"动作创建者(我们称之为thunk动作创建者),我们现在可以在任何我们使用常规动作创建者的地方使用它们.
从Dan Abramov本人那里检查这个很棒的答案,它涵盖了一切:https://stackoverflow.com/a/35415559/5714933
另请查看这些链接以获取更多信息:
https://github.com/gaearon/redux-thunk#motivation http://redux.js.org/docs/advanced/AsyncActions.html
| 归档时间: |
|
| 查看次数: |
9800 次 |
| 最近记录: |