• redux中间件函数


    middleware中间件函数

    中间件本质就是得到一个新的dispatch创建函数,调用创建函数,重写了store.dispatch(action),依次执行新的dispatch(action)方法,来改变store中的state
    我们从一个小案例来说明中间件函数的由来:

    我们需要记录一下操作类型action和下一个状态state

    //由action创建函数addTodo创建一个action对象
    const action = addTodo('Use Redux')
    //打印action对象
    console.log('dispatching', action)
    store.dispatch(action)
    //打印下一个状态
    console.log('next state', store.getState())
    

    这是我们想要的效果,但不想每次都这样做手动创建,我们希望用一个函数来自动创建

    封装dispatch函数

    将日志记录提取到函数中:

    
    function dispatch(store, action) {
       
      console.log('dispatching', action)
      store.dispatch(action)
      console.log('next state', store.getState())
    }
    '
    运行

    然后,在任何地方使用它,而不是store.dispatch():

    dispatch(store, addTodo('Use Redux'))
    

    我们可以到这里结束,但是每次都导入一个特殊的函数不是很方便。

    使用 Monkeypatching (猴子补丁)重写dispatch方法

    Monkeypatching 是一种黑客攻击。“替换任何你喜欢的方法”

    const next = store.dispatch  //保存源dispatch
    //重写dispatch
    store.dispatch = function dispatch(action) {
       
      console.log('dispatching', action)
      let result = next(action)   //调用原始的dispatch方法
      console.log('next state', store.getState(
  • 相关阅读:
    IDEA常用插件
    CorelDraw2024(CDR)- 矢量图制作软件介绍
    Unity中程序集dll
    【春秋云镜】CVE-2023-27179
    教程 | 线性回归分析模块使用介绍
    springboot笔记总结
    Linux常用指令(十)——服务器相关与互传文件
    聊聊如何实现 LRU 缓存算法
    沃尔玛Walmart EDI 850订单详解
    Springboot自动装配源码及启动原理理解
  • 原文地址:https://blog.csdn.net/CD_promise/article/details/126951471