如何在Redux应用程序中动态加载reducers进行代码拆分?

如何在Redux应用程序中动态加载reducers进行代码拆分?,第1张

如何在Redux应用程序动态加载reducers进行代码拆分?

这不是一个完整的答案,但应该可以帮助您入门。请注意,我并 没有丢弃旧的减速器- 我只是在组合列表中添加了新的减速器。我认为没有理由扔掉旧的减速器-即使在最大的应用程序中,您也不可能拥有成千上万的动态模块,这是您 可能 希望断开应用程序中某些减速器的连接点。

reducers.js
import { combineReducers } from 'redux';import users from './reducers/users';import posts from './reducers/posts';export default function createReducer(asyncReducers) {  return combineReducers({    users,    posts,    ...asyncReducers  });}
store.js
import { createStore } from 'redux';import createReducer from './reducers';export default function configureStore(initialState) {  const store = createStore(createReducer(), initialState);  store.asyncReducers = {};  return store;}export function injectAsyncReducer(store, name, asyncReducer) {  store.asyncReducers[name] = asyncReducer;  store.replaceReducer(createReducer(store.asyncReducers));}
routes.js
import { injectAsyncReducer } from './store';// Assuming React Router here but the principle is the same// regardless of the library: make sure store is available// when you want to require.ensure() your reducer so you can call// injectAsyncReducer(store, name, reducer).function createRoutes(store) {  // ...  const CommentsRoute = {    // ...    getComponents(location, callback) {      require.ensure([        './pages/Comments',        './reducers/comments'      ], function (require) {        const Comments = require('./pages/Comments').default;        const commentsReducer = require('./reducers/comments').default;        injectAsyncReducer(store, 'comments', commentsReducer);        callback(null, Comments);      })    }  };  // ...}

表达这一点可能有更整洁的方式-我只是在说明这个想法。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5566377.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-14
下一篇2022-12-14

发表评论

登录后才能评论

评论列表(0条)

    保存