文章目录
react-thunk
源码太短了:
const middleware: ThunkMiddleware<State, BasicAction, ExtraThunkArg> =
({
dispatch, getState }) =>
next =>
action => {
// The thunk middleware looks for any functions that were passed to `store.dispatch`.
// If this "action" is really a function, call it and return the result.
if (typeof action === 'function') {
// Inject the store's `dispatch` and `getState` methods, as well as any "extra arg"
return action(dispatch, getState, extraArgument)
}
// Otherwise, pass the action down the middleware chain as usual
return next(action)
}
return middleware
1,标准React中间件。
都是固定代码。
const middleware: ThunkMiddleware<State, BasicAction, ExtraThunkArg> =
({
dispatch, getState }) =>
next =>
action => {
//...
}
return middleware
2,Action是函数就调用,否则放行。
if (typeof action === 'function') {
return action(dispatch, getState, extraArgument)
}
return next(action)
总之,thunk只是支持函数式Action而已。
举例说明
计数器案例中的Action:
export const Normal = v => ({
type: "Normal", amount: v
})
export const Async = (v, time) => {
return (dispatch) => {
setTimeout(() => {
dispatch(Normal(v));
}, time);
}
}
thunk收到这个Action时,会直接调用它。执行内部的异步代码。
最终发出的还是同步的Action。