如何把 Redux 的导航状态同步到 App Shell?
解读
在国内一线前端面试中,面试官问“导航状态同步到 App Shell”通常不是单纯考 Redux 用法,而是考察候选人能否把路由状态(React-Router、Taro、Remix 等)与全局 Redux Store打通,并保证服务端渲染(SSR)、微前端主应用、小程序插件壳等 App Shell 场景下,首屏就能拿到正确的导航数据,避免“闪屏”“二次跳转”“SEO 失效”三大硬伤。回答时必须体现“数据流向可预测、可回溯、可测试”的 Redux 核心价值观,同时给出可落地的工程化方案。
知识点
- 导航状态本质:URL → Router → Location → Store,属于“派生数据”,但国内业务常要求把“当前选中菜单、面包屑、权限掩码”等计算后的元数据落盘到 Store,方便跨组件、跨 iframe、跨微应用读取。
- 单向数据流铁律:Router 是“唯一真相源”,Store 只能镜像不能抢占。
- 同步时机:
- 客户端:history.listen 触发 dispatch;
- SSR:StaticRouter 在loader阶段一次性注入 PRELOADED_STATE。
- 不可变更新:必须用 immer 或 slice reducer 保证 location、match、params 全链路不可变,否则时间旅行调试会失效。
- App Shell 特指:
- PWA 的壳层(service worker 预缓存);
- 微前端基座(qiankun 主应用);
- 小程序插件外壳(微信、支付宝)。
这些壳层首屏不等待 JS Bundle,因此需要把当前路由快照序列化到 HTML(window.__INITIAL_STATE__),否则会出现“白屏 → JS 加载完 → 再跳一次”的恶劣体验。
- 国内合规:必须兼容微信 JSSDK 的 history 模式限制、抖音小程序路由栈上限 10 层等特殊场景,否则会被业务方直接 veto。
答案
分四步落地,每一步都给出国内真实项目可抄的代码骨架。
第一步:定义导航子状态
// src/store/slices/navigationSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import type { Location } from 'history';
interface NavState {
location: Location;
match: Record<string, string>; // 参数映射
breadcrumb: Array<{ title: string; path: string }>;
permission: number; // 权限位
}
const initialState: NavState = {
location: {} as Location,
match: {},
breadcrumb: [],
permission: 0,
};
const navigationSlice = createSlice({
name: 'navigation',
initialState,
reducers: {
/** 仅 Router 可调用 */
syncLocation(state, action: PayloadAction<Omit<NavState, 'permission'>>) {
state.location = action.payload.location;
state.match = action.payload.match;
state.breadcrumb = calcBreadcrumb(action.payload.location.pathname);
},
/** 权限中心回调 */
syncPermission(state, action: PayloadAction<number>) {
state.permission = action.payload;
},
},
});
export const { syncLocation, syncPermission } = navigationSlice.actions;
export default navigationSlice.reducer;
第二步:Router → Store 单向同步
// src/router/syncRedux.ts
import { history } from '@/utils/history'; // 统一 hash/history 模式封装
import { syncLocation } from '@/store/slices/navigationSlice';
import { store } from '@/store';
export function startSync() {
const unsubscribe = history.listen((update) => {
const { location, match } = update;
store.dispatch(syncLocation({ location, match }));
});
// 首次挂载主动触发一次,防止 SSR 与 CSR 状态断层
const { location, match } = history.getCurrentLocation();
store.dispatch(syncLocation({ location, match }));
return unsubscribe;
}
在App.tsx顶层调用 startSync(),并保证在微前端卸载时执行 unsubscribe,防止内存泄漏。
第三步:Store → App Shell 快照同步
- 服务端(以 Node 中间层为例):
// server/middleware/render.tsx
import { StaticRouter } from 'react-router-dom/server';
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from '@/store';
import { syncLocation } from '@/store/slices/navigationSlice';
function render(url: string, ctx: any) {
const store = configureStore({ reducer: rootReducer });
// 1. 根据请求 URL 构造假 history
const staticHistory = createMemoryHistory({ initialEntries: [url] });
const { location, match } = computeMatch(staticHistory);
// 2. 把导航状态注入 Store
store.dispatch(syncLocation({ location, match }));
// 3. 序列化到 HTML
const html = ReactDOMServer.renderToString(
<StaticRouter location={url} context={ctx}>
<Provider store={store}>
<App />
</Provider>
</StaticRouter>
);
const state = store.getState();
return `
<html>
<head>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(state).replace(/</g, '\\u003c')}
</script>
</head>
<body>
<div id="root">${html}</div>
</body>
</html>
`;
}
- 客户端注水:
// src/main.tsx
const preloadedState = window.__INITIAL_STATE__;
const store = configureStore({ reducer: rootReducer, preloadedState });
// 必须再次执行一次 startSync,把后续跳转继续同步
startSync();
ReactDOM.hydrate(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
第四步:App Shell 消费
以 qiankun 主应用为例,在菜单高阶组件里直接读 Store,不再重新计算:
import { useSelector } from 'react-redux';
import type { RootState } from '@/store';
function GlobalMenu() {
const { breadcrumb, permission } = useSelector((s: RootState) => s.navigation);
return (
<a-breadcrumb>
{breadcrumb.map(b => (
<a-breadcrumb-item key={b.path}>{b.title}</a-breadcrumb-item>
))}
</a-breadcrumb>
);
}
至此,导航状态在服务端 → 壳层 → 微子应用全链路可预测、可回溯、可测试,且首屏无闪跳。
拓展思考
- 时间旅行调试:如果以后产品要求“后退到上一页时自动恢复滚动位置”,可直接在 navigationSlice 里加
scrollTop字段,利用 Redux DevTools 实现“步骤级回放”,而无需额外维护 scroll 缓存库。 - 权限动态化:国内很多项目把“按钮级权限”也塞进导航状态,导致 Store 体积膨胀。建议把权限位与导航元数据分层,导航只存“可见菜单掩码”,具体按钮权限走 React Context + Suspense 按需加载,避免 Store 成为“大杂烩”。
- 小程序壳场景:微信插件无法访问
window.__INITIAL_STATE__,可把初始状态通过插件接口参数传入,再在插件内rehydrate到 Redux,实现“小程序插件 → Redux”同步,保证同一套代码三端运行。