使用 redux-first-history 实现集中式路由状态。
解读
在国内 React 技术栈面试中,面试官常把“路由状态是否该进 Redux”作为区分初中高级的分水岭。
传统 react-router-dom 把路由状态放在组件内部,导致时间旅行调试、权限埋点、服务端渲染等环节无法统一回溯。
redux-first-history 的核心价值就是把 history 实例完全托管到 Redux,让每一次 push/replace/go 都变成一次可预测的 action,从而满足“单一数据源”原则。
面试官想听你回答:
- 为什么不用 connected-react-router(社区已半弃坑)
- 如何与 react-router v6 并存
- 如何防止“双写”导致死循环
- 如何与权限、埋点、面包屑等强耦合场景结合
知识点
- history 库的内部机制:memory/browser/hash 三种模式,action 类型为 POP/PUSH/REPLACE,location 对象包含 pathname/search/state
- redux-first-history 的 middleware 原理:监听 history.listen,把每一次变更转成 LOCATION_CHANGE action,同时阻止组件侧直接调用 history.push,强制走 dispatch
- reducer 合并技巧:使用 combineReducers 时,必须把 router 节点挂到顶层且 key 固定为 router,否则中间件无法正确映射
- react-router v6 兼容:需用 unstable_HistoryRouter 替代 BrowserRouter,并把 createReduxHistory 返回的 history 实例注入
- 性能陷阱:LOCATION_CHANGE 每次都会触发全树 ConnectedRouter 重新渲染,必须用 React.memo + useSelector 浅比较 pathname 才能避免卡顿
- SSR 同构:服务端先 createMemoryHistory,生成静态路由状态后脱水,客户端再 hydrate,保证首屏路由状态不丢失
- 类型安全:在 TypeScript 下需声明 RootState['router'] 为 RouterState,否则 useSelector(state => state.router.location) 会推导为 any
答案
- 安装与初始化
npm i redux-first-history history@5 react-router-dom@6
// store.ts
import { configureStore } from '@reduxjs/toolkit';
import { createReduxHistory, routerMiddleware, routerReducer } from 'redux-first-history';
import { createBrowserHistory } from 'history';
const history = createBrowserHistory(); // 也可 createMemoryHistory 用于 SSR
const middleware = routerMiddleware(history);
export const store = configureStore({
reducer: {
router: routerReducer, // 必须叫 router
// 其他业务 reducer
},
middleware: (getDefault) => getDefault().concat(middleware),
});
export const reduxHistory = createReduxHistory(store, history);
- 顶层注入
// index.tsx
import { unstable_HistoryRouter as HistoryRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { store, reduxHistory } from './store';
root.render(
<Provider store={store}>
<HistoryRouter history={reduxHistory}>
<App />
</HistoryRouter>
</Provider>
);
- 跳转统一走 dispatch
import { push } from 'redux-first-history';
function jump() {
store.dispatch(push('/order/detail?id=123'));
}
- 组件内读取
const location = useSelector((s: RootState) => s.router.location);
const query = new URLSearchParams(location.search);
- 权限拦截示例
const authMiddleware: Middleware = () => (next) => (action) => {
if (action.type === 'router/push' && action.payload.pathname.startsWith('/admin')) {
const token = store.getState().user.token;
if (!token) {
return next(push('/login?redirect=' + encodeURIComponent(action.payload.pathname)));
}
}
return next(action);
};
- 埋点上报
store.subscribe(() => {
const prev = prevRouterRef.current;
const next = store.getState().router.location;
if (prev.pathname !== next.pathname) {
report('pageview', { path: next.pathname });
}
prevRouterRef.current = next;
});
通过以上步骤,路由状态完全进入 Redux DevTools,支持时间旅行、热重载、回放测试,同时与业务状态同构,满足大型项目“可预测、可回溯、易测试”的硬性指标。
拓展思考
- 微前端场景:qiankun 子应用切换时,主应用 history 与子应用 history 隔离,可通过 redux-first-history 把主应用路由状态同步到全局 Store,子应用只读不写,避免多实例冲突。
- React Native:在 RN 中无浏览器 history,需用 createMemoryHistory,并结合 react-navigation 的 deep link 映射,把 URL 与 state 双向同步,实现“一套代码,三端运行”。
- 数据预取:在 LOCATION_CHANGE action 触发后,利用 Redux-Saga 的 takeLatest 监听,自动根据 pathname 匹配数据字典,并行请求接口,把瀑布式请求提前到路由切换瞬间,首屏可缩短 200~300 ms。
- 灰度发布:在 reducer 层面对路由做 A/B 映射,比如 /home 在灰度组命中时重定向到 /home/v2,全程无组件侵入,回滚只需改配置即可。
- 未来演进:React Router v6.4 的 createBrowserRouter 已自带 Data API,社区可能出现 redux-first-history 的替代方案,但“路由状态归一”思想不会改变,候选人应以不变驭万变,重点阐述设计哲学而非 API 记忆。