react如何写自己写中间件
自定义中间件的实现方法
在React中实现自定义中间件通常涉及Redux或React Router等库的中间件机制。以下是两种常见场景的实现方式:
Redux中间件实现
Redux中间件允许在action被派发到reducer之前或之后执行自定义逻辑。基本结构遵循Redux的中间件签名:
const customMiddleware = store => next => action => {
// 前置逻辑:例如日志记录、权限校验
console.log('Dispatching action:', action);
// 调用next传递action到下一个中间件或reducer
const result = next(action);
// 后置逻辑:例如状态变更后的处理
console.log('New state:', store.getState());
return result;
};
关键点:
store参数包含getState和dispatch方法next是中间件链中的下一个函数action是当前处理的Redux action
应用示例:
import { createStore, applyMiddleware } from 'redux';
const store = createStore(
rootReducer,
applyMiddleware(customMiddleware, otherMiddleware)
);
React Router中间件实现
对于路由级别的拦截或处理,可通过高阶组件或自定义history对象实现:
const routeMiddleware = (history) => {
const originalPush = history.push;
history.push = (path, state) => {
// 路由跳转前的逻辑(如鉴权)
if (!isAuthenticated(path)) {
return originalPush('/login');
}
return originalPush(path, state);
};
return history;
};
使用方式:
import { createBrowserHistory } from 'history';
const enhancedHistory = routeMiddleware(createBrowserHistory());
<Router history={enhancedHistory}>
{/* Routes */}
</Router>
通用中间件模式
若需实现独立于框架的中间件,可参考洋葱模型设计:
function composeMiddlewares(middlewares) {
return (context) => {
let index = -1;
function dispatch(i) {
if (i <= index) throw new Error('Next called multiple times');
index = i;
const fn = middlewares[i] || ((ctx) => ctx);
return fn(context, () => dispatch(i + 1));
}
return dispatch(0);
};
}
使用示例:
const middlewares = [
(ctx, next) => { console.log('Start'); next(); },
(ctx, next) => { ctx.data = 'processed'; next(); }
];
const processor = composeMiddlewares(middlewares);
processor({});
注意事项
- 中间件应保持纯函数特性,避免副作用
- 明确中间件的执行顺序对结果的影响
- 异步操作需返回Promise或使用async/await
- 考虑错误处理机制,可通过try/catch包裹next调用







