【问题标题】:Redux splitting reducers - export several in one fileRedux 拆分 reducers - 在一个文件中导出多个
【发布时间】:2019-09-18 06:17:41
【问题描述】:

我正在尝试获得这样的状态形状:

state = {
  items: {
    currentItem: object,
    byId: object,
    allIds: array,
    fetching: bool
  },
  someOtherModule = { ... }
}

我已将我的 items reducer 拆分为两个文件,试图不在一个文件中包含所有内容;请注意,这只是伪代码来说明我在做什么 -

items/reducers/currentItem.js

const currentItem = (state = null, action) => ...
export default currentItem;

我试过这样:

items/reducers/items.js

const byId = (state = {}, action) => ...
const allIds = (state = [], action) => ...
const fetching = (state = false, action) => ...
export default {byId, allIds, fetching};

items/reducers/index.js

import { combineReducers } from 'redux';
import item from './item';
import currentItem from './currentItem';

export default combineReducers({ item, currentItem });

我已经尝试过这种方式:

items/reducers/items.js

export const byId = (state = {}, action) => ...
export const allIds = (state = [], action) => ...
export const fetching = (state = false, action) => ...

items/reducers/index.js

import { combineReducers } from 'redux';
import * as item from './item';
import currentItem from './currentItem';

export default combineReducers({ item, currentItem });

我最终得到了一个只有 currentItem 而没有“items”的“root items reducer”。

如果我在 items.js 中导出 combineReducers({byId, allIds, fetching}) 它可以工作,但它会为我的状态增加一个级别:

state = {
      items: {
        currentItem: object,
        items: { 
         byId: object,
         allIds: array,
         fetching: bool
        }
      },

【问题讨论】:

    标签: javascript ecmascript-6 redux es6-modules


    【解决方案1】:

    想通了; combineReducers 期望一个对象,其键是 reducer 名称,值是 reducer 函数(TLDR - 阅读手册):

    items/reducers/items.js

    export const byId = (state = {}, action) => ...
    export const allIds = (state = [], action) => ...
    export const fetching = (state = false, action) => ...
    

    items/reducers/index.js

    import { combineReducers } from 'redux';
    import { byId, allIds, fetching } as item from './item';
    import currentItem from './currentItem';
    
    export default combineReducers({ byId, allIds, fetching, currentItem });
    

    我想我会把所有东西都放回一个文件中,这样更简单。

    【讨论】:

    • 在问题版本上做export default combineReducers({ ...item, currentItem });应该可以让你到达那里
    • @enapupe - 不错!
    猜你喜欢
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2017-08-24
    相关资源
    最近更新 更多