redux中间件原理

本文探讨了Redux中间件的实现原理,从增强store的dispatch方法开始,逐步介绍如何为dispatch添加多个功能,避免在每个函数中替换dispatch,以及如何通过参数直接传入新的dispatch函数,以此实现对Redux应用的扩展和定制。
摘要由CSDN通过智能技术生成

redux中间件实现原理

1.开始 --> 增强store的dispath方法,使用额外的方法将原始方法进行替换

    let dispath = store.dispath;
    function log(action) {
      console.log('....')
      let re = dispath(action);
      console.log('....');
      return re;
    }
    store.dispath = log;

2.继续 --> 对dispath增加超过一个的功能

  function run1(store) {
    let dispath = store.dispath;
    store.dispath = function log (action) {
      console.log('...')
      let re = dispath(action);
      console.log('....')
      return re;
    }
  }

  function run2(store) {
    let dispath = store.dispath;
    store.dispath = function get (action) {
      console.log('...')
      let re = dispath(action);
      console.log('....')
      return re;
    }
  }

  run1(store)
  run2(store)

3.然后 --> 不在每一个函数中替换dispath函数,而是直接返回新的dispath,再将store的原始dispath进行统一替换

  function run1(store) {
    let dispath = store.dispath;
    return function log (action) {
      console.log('...')
      let re = dispath(action);
      console.log('....')
      return re;
    }
  }

  function run2(store) {
    let dispath = store.dispath;
    return function get (action) {
      console.log('...')
      let re = dispath(action);
      console.log('....')
      return re;
    }
  }

  // 在redux内部进行转换
  function applyMiddlewareByMonkeypatching(store, middlewares) {
    middlewares = middlewares.slice()
    middlewares.reverse()

    middlewares.forEach(middleware =>
      store.dispatch = middleware(store)
    )
  }

4.最后 --> 每一个中间件不是通过store获取dispath函数,而是直接通过参数传入行一个middleware返回的新的函数

  function run1(store) {
    // 上一个中间价转换后并返回的dispath
    return function(next) {
      return function log (action) {
        console.log('...')
        let re = next(action);
        console.log('....')
        return re;
      }
    }
  }

  //在redux内部进行转换
  function applyMiddleware(store, middlewares) {
    middlewares = middlewares.slice()
    middlewares.reverse()
    
    // 使用reduce进行中间件的dispath转换
    store.dispath = middlewares.reduce((pre, current) => current(store)(pre), store.dispath)
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值