Redux Splitting Reducer-在一个文件中导出多个

时间:2019-04-29 15:30:35

标签: javascript ecmascript-6 redux es6-modules

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

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

我已将我的物品减速器分成两个文件,试图不将所有内容都放在一个文件中。请注意,这只是用来说明我在做什么的伪代码-

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”。

如果我在items.js中导出combineReducers({byId, allIds, fetching}),则可以使用,但是会为我的状态添加一个级别:

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

1 个答案:

答案 0 :(得分:0)

弄清楚了; CombineReducers期望对象的键是化简器名称,值是化简器功能(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 });

我想我会将所有内容都放回到一个文件中,这样更简单。