美文网首页
redux源码浅析之applyMiddleware

redux源码浅析之applyMiddleware

作者: cb12hx | 来源:发表于2018-03-31 14:12 被阅读0次

    还是先直接上代码

    export default function applyMiddleware(...middlewares) {
      return (createStore) => (reducer, preloadedState, enhancer) => {
        const store = createStore(reducer, preloadedState, enhancer)
        let dispatch = store.dispatch
        let chain = []
    
        const middlewareAPI = {
          getState: store.getState,
          dispatch: (action) => dispatch(action)
        }
        chain = middlewares.map(middleware => middleware(middlewareAPI))
        dispatch = compose(...chain)(store.dispatch)
    
        return {
          ...store,
          dispatch
        }
      }
    }
    

    再来看看我们用到的地方,在我们createStore时

    return enhancer(createStore)(reducer, preloadedState)
    

    再来看看我们的业务代码中怎么使用的

     const store = createStore(rootReducer, initialState, compose(
        applyMiddleware(...middlewares),
        devToolsExtension
      ))
    

    有几点要说明下

      1. createStore时,增强器是为了丰富dispatch功能的
      1. compose是为了叠加执行方法的,由上一篇我们知道,就是传入一个值,然后对这个值进行丰富
        综上所述,applyMiddleWare就是为了丰富dispatch的

    相关文章

      网友评论

          本文标题:redux源码浅析之applyMiddleware

          本文链接:https://www.haomeiwen.com/subject/cupgcftx.html