动态注入 store 的意义是因为使用 react-router 时一般使用了 code spliting,这样组件会作为 chunk 动态加载。
而这时候如果还像以前那样处理 store,则会在一开始就把全部 store 注入组件,造成浪费。所以,还要在 code soliting 组件的同时,动态注入 store。最开始只加载最基本的 store (如权限等)。
<Provider store={store}>
<Router history={history}>
<Route
name="注入测试"
path="injectReducer"
getComponent={async (location, callback) => {
const Component = await import('../containers/AssetOverview');
const reducers = await import('../containers/AssetOverview/reducers');
injectReducer(store, reducers); // 植入reducer
callback(null, Component.default);
}}
/>
</Router>
</Provider>
getComponent
是 react-router v2 的写法,升级到 v4 之后,不再提供动态加载组件的方法,只能通过 react-loadable 来动态加载组件。具体写法参见 https://zhuanlan.zhihu.com/p/31178105