redux-logger
打印日志中间件
let reduxLogger = (store) => (dispatch) => (action) =>{ console.log(store.getState()) dispatch(action) console.log(store.getState()) }复制代码
redux-thunk
处理异步请求
let reduxThunk = (store) => (dispatch) => (action) =>{ if(typeof action =='function'){ return action(dispatch,store.getState) } dispatch(action) }复制代码
redux-promise
处理promise
let reduxPromise = (store) => (dispatch) => (action) =>{ let reduxPromise = (store) => (dispatch)=> (action)=>{ if(action.then && typeof action.then === 'function'){ // 如果返回的是一个promise 那么不会处理失败逻辑 return action.then(dispatch) } if(action.payload && action.payload.then&& typeof action.payload.then ==='function'){ return action.payload.then(function(data){ action.payload = data; dispatch(action); },function(err){ action.payload = err; dispatch(action); return Promise.reject(err); }) } return dispatch(action); } }复制代码
applyMiddlewares
let applyMiddlewares = (middlewares)=>(createStore)=>(reducer)=>{ let store = createStore(reducer); let chain = middlewares.map(middleware=>middleware(store)) dispatch = compose(...chain)(store.dispatch); return { ...store, dispatch } } // compose let compose = (funcs)=>{ return funcs.reduce((a,b)=>(...args)=>a(b(...args))) }复制代码
简要总结
- redux 中间件都是一共返回三阶函数分别传递参数store、dispatch(源码里面是next)、action。
- applymiddleware 也是一共三阶函数,分别传递参数为middlewares、createStore、reducer。内部实现为先通过createStore和reducer获取store,然后middleware执行传递store,中间件组合执行传递store.dispatch生成强化后的dispatch,最后覆盖之前老的dispatch