中间件 解决了action 只能为对象的问题,可以传入异步函数
我举个具体例子,方便理解 本质就是高阶函数,目的就是为了保障reducer 函数的纯函数特性,因为异步操作,不可控
const thunkMiddleware = (store) => (next) => (action) => { if (typeof action === 'function') { return action(store.dispatch, store.getState); } return next(action); };
const step1 = thunkMiddleware(store);
const step2 = step1(next);
// 或等价于:
const step2 = thunkMiddleware(store)(next);
eg:
dispatch(fetchUser()); // fetchUser 返回一个函数!
const step3 = fetchUser()(store.dispatch, store.getState);
其实说穿了,就是通过函数参数,传递dispatch 来让action函数,内部拥有dispatch的能力罢了