当前位置: 首页 > news >正文

React@16.x(60)Redux@4.x(9)- 实现 applyMiddleware

目录

  • 1,applyMiddleware 原理
  • 2,实现
    • 2.1,applyMiddleware
      • 2.1.1,compose 方法
      • 2.1.2,applyMiddleware
    • 2.2,修改 createStore

接上篇文章:Redux中间件介绍。

1,applyMiddleware 原理

Redux 应用中间件方式:

const store = createStore(reducer, applyMiddleware(logger1, logger2));

实际会转为下面的方式执行:

const store = applyMiddleware(logger1, logger2)(createStore)(reducer)
  • applyMiddleware 会确定用到的中间件;它会返回一个用来创建仓库的函数A,参数createStore
  • 函数 A,会返回创建仓库的函数B,和 createStore 函数差不多。
  • 函数B,会对中间件函数做处理,并修改原始 dispatch

大致相当于:

export const applyMiddleware = (...middlewares) => {// 用来创建的仓库的函数return (createStore) => {// 创建仓库的函数return (reducer, defaultState) => {const store = createStore(reducer, defaultState)const dispatch = '经过 middlewares 处理的 store.dispatch'return {...store,dispatch}}}
}

2,实现

2.1,applyMiddleware

上篇文章介绍了 中间件函数 的写法和多个中间件函数的执行顺序。

基于此,实现这个 dispatch 流转的逻辑,并得到最终的 dispatch 即可完成 applyMiddleware

2.1.1,compose 方法

关键要实现

const resultDispatch = logger1(logger2(logger3(store.dispatch)))

实现:

/*** @param  {...any} funcs* @returns {function}*/
export const compose = (...funcs) => {if (funcs.length === 0) {return (args) => args;} else if (funcs.length === 1) {return funcs[0];}return (...args) => {let lastReturn = null;for (let i = funcs.length - 1; i >= 0; i--) {const func = funcs[i];if (i === funcs.length - 1) {lastReturn = func(...args);} else {lastReturn = func(lastReturn);}}return lastReturn;};
};
// 测试代码
const add = (n) => {return n + n;
};const mult = (n) => {return n * n;
};const b = compose(add, mult);
console.log(b(3)); // 先乘后加,18

可使用 Array.reduce 简化:

export const compose = (...funcs) =>funcs.reduce((prev, next) =>(...args) =>prev(next(...args)));

2.1.2,applyMiddleware

import { compose } from "./compose";
export const applyMiddleware = (...middlewares) => {return (createStore) => {return (reducer, defaultState) => {const store = createStore(reducer, defaultState);let dispatch = () => {throw new Error("目前还不能使用 dispatch");};// 传递给中间件函数的 store 只有这2个属性。const simpleStore = {getState: store.getState,dispatch: (...args) => dispatch(...args), // 每个中间件函数的 dispatch 都是上一个中间件组装后的};// 获取用于创建 dispatch 的函数const dispatchProducts = middlewares.map((m) => m(simpleStore));// 重新组装后的 dispatchdispatch = compose(...dispatchProducts)(store.dispatch);return {...store,dispatch,};};};
};

2.2,修改 createStore

之前实现的 createStore,没有对可能的第3个函数做处理。这里补充下:

  • 如果第2个参数是 applyMiddleware,那说明没有 defaultState

这里就简单判断写第2个参数是不是函数,实际源码中 defaultState 也可以通过一个函数创建。

export const createStore = (reducer, defaultState, enhancer) => {// enhancer 表示 applymiddleware 返回的函数。if (typeof defaultState === 'function') {enhancer = defaultStatedefaultState = undefined}if (typeof enhancer === 'function') {enhancer(createStore)(reducer, defaultState)}// 其他剩余代码没有做变动。// ...
}

完整代码

export const createStore = (reducer, defaultState, enhancer) => {// enhancer 表示 applymiddleware 返回的函数。if (typeof defaultState === "function") {enhancer = defaultState;defaultState = undefined;}if (typeof enhancer === "function") {enhancer(createStore)(reducer, defaultState);}let currentReducer = reducer;let currentState = defaultState;let listeners = [];const dispatch = (action) => {if (typeof action !== "object" || Object.getPrototypeOf(action) !== Object.prototype) {throw new Error("action 必须是一个 plain Object");}if (action.type === undefined) {throw new Error("action 必须有 type 属性");}currentState = currentReducer(currentState, action);// 每次更新时,遍历监听器。for (const listener of listeners) {listener();}};const getState = () => {return currentState;};const subscribe = (listener) => {listeners.push(listener);let isRemove = false;// 取消监听return () => {if (isRemove) {return;} else {isRemove = true;listeners = listeners.filter((f) => f !== listener);}};};// createStore 创建时会调用一次。dispatch({type: `@@redux/INIT${getRandomString}`,});return {dispatch,getState,subscribe,};
};function getRandomString() {return Math.random().toString(36).substring(2, 8).split("").join(".");
}

以上。

http://www.lryc.cn/news/401666.html

相关文章:

  • level 6 day1 Linux网络编程之网络基础
  • PostgreSQL UPDATE 命令
  • 什么? CSS 将支持 if() 函数了?
  • function calling实现调用理杏仁api获取数据
  • Excel中用VBA实现Outlook发送当前工作簿
  • 从 ArcMap 迁移到 ArcGIS Pro
  • WSL2 的安装与运行 Linux 系统
  • 业务终端动态分配IP-DHCP技术、DHCP中继技术
  • 新一代大语言模型 GPT-5 对工作与生活的影响及应对策略
  • AI基于大模型语言存在的网络安全风险
  • 探索Perl语言:入门学习与实战指南
  • dp or 数学问题
  • kibana连接elasticsearch(版本8.11.3)
  • 基于python的图像去水印
  • Linux下Supervisor的安装与配置
  • 使用Pandas读取Excel文件将特定列转成str格式方法汇总
  • FPGA CFGBVS 管脚接法
  • 快速排序及归并排序的实现与排序的稳定性
  • 【系统架构设计】数据库系统(一)
  • 泛微e-cology WorkflowServiceXml SQL注入漏洞(POC)
  • <Rust><GUI>rust语言GUI库tauri体验:前、后端结合创建一个窗口并修改其样式
  • OBD诊断(ISO15031) 09服务
  • 客户端与服务端之间的通信连接
  • Font Awesome 图表图标
  • React Native 自定义 Hook 获取组件位置和大小
  • 如何在SpringCloud中使用Kafka Streams实现实时数据处理
  • InterSystems IRIS使用python pyodbc连接 windows环境,odbc驱动安装,DSN配置,数据源配置
  • JVM:运行时数据区
  • spring-boot2.x整合Kafka步骤
  • 信创学习笔记(四),信创之数据库DB思维导图