Redux中间件(Middleware) 实现原理

767 阅读2分钟

Redux中间件(Middleware)

中间件:类似于插件,可以在不影响原本功能、并且不改动原本代码的基础上,对其功能进行增强。在Redux中,中间件主要用于增强dispatch函数。

实现Redux中间件的基本原理,是更改仓库中的dispatch函数。

简单场景

比如要打印store变化前后的数据

import { createStore, bindActionCreators } from "../redux";
import reducer from "./reducer"


const store = createStore(reducer);
const oldDispatch = store.dispatch; //保留原本的dispatch函数
store.dispatch = function (action) { //更改store中的dispatch
    console.log("中间件1")
    console.log("旧数据", store.getState());
    console.log("action", action);
    oldDispatch(action);
    console.log("新数据", store.getState());
    console.log("")
}

这么写代码吗?? 肯定不是。。 其实核心原理就是保存之前的dispatch函数,给下一个中间件用。

真正实现手写中间件

Redux中间件书写:

  • 中间件本身是一个函数,该函数接收一个store参数,表示创建的仓库,该仓库并非一个完整的仓库对象,仅包含getState,dispatch。该函数运行的时间,是在仓库创建之后运行。
    • 由于创建仓库后需要自动运行设置的中间件函数,因此,需要在创建仓库时,告诉仓库有哪些中间件
    • 需要调用applyMiddleware函数,将函数的返回结果作为createStore的第二或第三个参数。
  • 中间件函数必须返回一个dispatch创建函数
//中间件本身是一个函数,该函数接收一个store参数
export const journalMiddle = function (store) {
    //中间件函数必须返回一个dispatch创建函数 next是中间件组件前后传递的新dispatch 而非store的dispatch
    return function (next) {
        //dispatch创建函数
        return function (action) {

            console.log("journalMiddle pre store state", store.getState());

            next(action);

            console.log("journalMiddle new store state", store.getState());

        };

    };

};

//index.js 应用
import { createStore, bindActionCreators, applyMiddleware } from "redux";

import redercer from "./reducer/index.js";

import * as actionAll from "./action/number-action";

import { journalMiddle } from "./writeMiddleware/index";



const store = createStore(redercer, applyMiddleware(journalMiddle));

打印结果如下

image.png

这样就做到了打印日志的需求

多个中间件dispatch的传递过程是??? 看下图

image.png