我要搬到Reduxgo .

我的应用程序由很多部分(页面、组件)组成,所以我想创建许多简化程序.Redux示例表明,我应该使用combineReducers()生成一个减速机.

此外,据我所知,Redux应用程序应该有一个存储区,它是在应用程序启动后创建的.当store 创建时,我应该通过我的组合减速器.如果应用程序不是太大,这是有意义的.

但是,如果我构建多个JavaScript包怎么办?例如,应用程序的每个页面都有自己的Bundle 包.我认为在这种情况下,一个组合式减速器不太好.我查看了Redux的源代码,发现有replaceReducer()个函数.这似乎就是我想要的.

我可以为我的应用程序的每个部分创建组合减速器,当我在应用程序的各个部分之间移动时使用replaceReducer().

这是一个好方法吗?

推荐答案

Update: see also how Twitter does it.

这不是一个完整的答案,但应该可以帮助你开始.请注意,我已经not throwing away old 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));
}

路由.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);
      })
    }
  };

  // ...
}

可能有更好的方式来表达这一点-我只是展示一下 idea .

Javascript相关问答推荐

用相器进行向内碰撞检测

fetch在本地设置相同来源的cookie,但部署时相同的代码不会设置cookie

是什么原因导致此Angular 16电影应用程序中因类型错误而不存在属性?

每次子路由重定向都会调用父加载器函数

窗口.getComputedStyle()在MutationObserver中不起作用

Angular中计算信号和getter的区别

从Node JS将对象数组中的数据插入Postgres表

我的服务工作器没有连接到我的Chrome扩展中的内容脚本.我该怎么解决这个问题?

如何在bslib nav_insert之后更改导航标签的CSS类和样式?

使用js构造一个html<;ath&>元素并不能使其正确呈现

让chart.js饼图中的一个切片变厚?

将数组扩展到对象中

面对代码中的错误作为前端与后端的集成

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

AddEventListner,按键事件不工作

Next.js无法从外部本地主机获取图像

重新呈现-react -筛选数据过多

如何在Jest中模拟函数

有角粘桌盒阴影

KeyboardEvent:检测到键具有打印的表示形式