美文网首页
02从源码角度看applyMiddleware

02从源码角度看applyMiddleware

作者: zdxhxh | 来源:发表于2019-12-26 10:45 被阅读0次

applyMiddleware

该函数为createStore的enhancer函数,通过传入中间件对store的dispatch方法进行改造

传统的装饰者模式 :

function onload(fn) { 
  if(typeof window.onload === 'function') { 
    // 缓存原有加载事件函数
    let oldOnload = window.onload 
    window.onload = function() { 
      oldOnload()
      fn()
    }
  }
}

补充 : 装饰者模式: 在不改变原对象的基础上,通过对其进行包装拓展,添加属性或者方法,使得原有对象可以满足开发者更深层次的需求

对以上函数以依赖注入的形式重构

function onload(fn,dom) { 
  if(typeof dom.onload === 'function') { 
    // 缓存原有加载事件函数
    let oldOnload = window.onload 
    dom.onload = function() { 
      oldOnload()
      fn()
    }
  }
}

再对其进行柯里化

function onload(fn) { 
  return dom=> { 
    if(typeof dom.onload === 'function') { 
      // 缓存原有加载事件函数
      let oldOnload = window.onload 
      dom.onload = function() { 
        oldOnload()
        fn()
      }
    }
  }
}

再来看看applyMiddleware

function applyMiddleware(...middlewares) {
  // 返回一个接受 createStore的函数 
  return createStore => (...args) => {
    // 创建一个store e
    const store = createStore(...args)
    let dispatch = () => {
      throw new Error(
        `Dispatching while constructing your middleware is not allowed. ` +
          `Other middleware would not be applied to this dispatch.`
      )
    }
    const middlewareAPI = {
      getState: store.getState,
      dispatch: (...args) => dispatch(...args)
    }
    // 遍历执行中间件
    const chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)
    return {
      ...store,
      // 覆盖原有store的dispatch
      dispatch
    }
  }
}

这个方法没有对createStore重写赋值,仅仅是调用了createStore,这也避免了污染createStore函数

请看createStore这段代码

export default function createStore(reducer,preLoadState,enhancer) { 
  if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error('Expected the enhancer to be a function.')
    }
    return enhancer(createStore)(reducer, preloadedState)
  }
}

相关文章

网友评论

      本文标题:02从源码角度看applyMiddleware

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