1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
function createThunkMiddleware(extraArgument) { return ({ dispatch,getState }) => next => action => { if (typeof action === 'function') { return action(dispatch,getState,extraArgument); }
return next(action); }; }
const thunk = createThunkMiddleware(); thunk.withExtraArgument = createThunkMiddleware;
{ getState: store.getState, dispatch: (...args) => dispatch(...args) }
如果 action 是一个函数, thunk 中间件会拦截执行 action, 如果 action 是一个对象, 则执行 next 方法, next 就是 thunk 下一个中间件 action => { ... }, 因为正常情况下 action 一般是 对象, 所以方法会一直执行,按照 middleware 数组顺序
action => { if (typeof action === 'function') { return action(dispatch,extraArgument); }
return next(action); }
这里有一点疑问的是 action(dispatch,extraArgument)
action 里面的 dispatch 是一个空方法,只是最后在 applyMiddleWare dispatch 最后会被覆盖 在之前的 v3 dispatch 就是 store.dispatch,后面 v4 dispatch 改成 空方法,那这里的 dispatch 方法就没有 dispatch 的功能了,具体可以看这个 [issue](https: 如果你对这里有什么还得理解,欢迎沟通
|