zoukankan      html  css  js  c++  java
  • redux中间件之monkeying patch

    我们想在reudx代码间插入想要做的逻辑,其实就是中间件。

    1.基本做法(假设已经配置好react-redux也就是store/index,addAction和subAction是action逻辑)

    import store from './store/index.js'
    
    import {addAction,subAction} from './store/actionCreators'
    
    //1.基本做法
    
    console.log("dispatch前---dispathing", addAction(10))
    
    store.dispatch(addAction(10))
    
    console.log("dispatch后---new state", store.getState())
    
    console.log("dispatch前---dispathing", addAction(15))
    
    store.dispatch(addAction(15))
    
    console.log("dispatch后---new state", store.getState())

    这样做简单但是调用起来很复杂

    2.封装函数

    function dispatchAndLogging(action){
    
      console.log("dispatch前---dispathing", action)
    
      store.dispatch(action)
    
      console.log("dispatch后---new state", store.getState())
    
    }
    
    dispatchAndLogging(addAction(10))
    
    dispatchAndLogging(addAction(15))


    3.在函数的基础上修改原有的dispatch

    const next = store.dispatch
    
    function dispatchAndLogging2(action){
    
      console.log("dispatch前---dispathing", action)
    
      next(action)
    
      console.log("dispatch后---new state", store.getState())
    
    }
    
    store.dispatch = dispatchAndLogging2
    
    store.dispatch(addAction(10))
    
    store.dispatch(addAction(5))

    这就不会影响原来的调用,也就是monkeyingpatch。但是可能污染了原来的store

    4.最后封装一下再使用

    function patchLogging(store) {
    
      const next = store.dispatch
    
      function dispatchAndLogging(action){
    
        console.log("dispatch前---dispathing", action)
    
        next(action)
    
        console.log("dispatch后---new state", store.getState())
    
      }
    
      return dispatchAndLogging
    
    }
    
    patchLogging(store)
    
    //应用封装好的中间件
    
    function applyMiddlewares(...middlewares){
    
      middlewares.forEach(middleware=>{
    
        store.dispatch=middleware(store)
    
      })
    
    }
    
    applyMiddlewares(patchLogging)
  • 相关阅读:
    个性化联邦学习算法框架发布,赋能AI药物研发
    ES入门 (2) 数据格式/类型
    ES入门 (1) 使用基础(1)安装(1) WIN 单机
    Java 之 JDBC:(十)Spring的JDBCTemplate
    Java 之 JDBC:(九)Apache-DBUtils实现CRUD操作
    Java 之 JDBC:(八)数据库连接池
    Java 之 JDBC:(七)DAO及相关实现类
    Java 之 JDBC:(六)数据库事务
    Java 之 JDBC:(五)批量插入
    第七节:循环结构
  • 原文地址:https://www.cnblogs.com/haoqirui/p/14855781.html
Copyright © 2011-2022 走看看