项目安装redux-thunk中间件
npm install redux-thunk -S
项目引入redux-thunk,并且使用redux-thunk
action不再返回对象,而是返回一个函数,这里用延时器模拟异步请求
这样redux就可以做异步操作了。
redux-thunk源码解读
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;
export default thunk;
在这里我们看到redux的源码其实只有11行,主要内容就是判断action是否是一个函数,如果是一个函数就传递参数dispatch,需要手动派发action给reducer,而如果不是一个函数,就自动派发action给reducer,从而加强action的派发功能。