栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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);      })    }  };  // ...}

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/575148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号