Redux中间件原理
以下是关于 Redux 中间件原理 的系统梳理:
一、中间件的核心作用
- 扩展 Dispatch 能力:处理非普通对象类型的 Action(如函数、Promise)
- 流程拦截:在 Action 到达 Reducer 前进行预处理
- 功能增强:添加日志、异步处理、错误监控等能力
- 链式处理:多个中间件形成处理管道
二、中间件架构三要素
要素 | 作用 | 示例 |
---|---|---|
柯里化结构 | 分层接收 store/next/action | store => next => action => |
执行顺序控制 | 决定中间件的处理顺序 | 从右到左组合 |
链式传递机制 | 通过 next 连接中间件链条 | next(action) |
三、中间件核心实现原理
-
中间件签名结构
const middleware = store => next => action => { // 前置处理 const result = next(action); // 传递 Action // 后置处理 return result; };
-
中间件组合机制
function applyMiddleware(...middlewares) { return createStore => (reducer, preloadedState) => { const store = createStore(reducer, preloadedState); const middlewareAPI = { getState: store.getState, dispatch: (action) => dispatch(action) }; // 初始化中间件链 const chain = middlewares.map(middleware => middleware(middlewareAPI)); dispatch = compose(...chain)(store.dispatch); return { ...store, dispatch }; }; }
-
组合函数 compose
function compose(...funcs) { return funcs.reduce((a, b) => (...args) => a(b(...args))); }