6

我刚开始使用 normalizr 来管理我的状态。我已经到了以下代码更新所需对象的地步,但我无法以干净、干燥的方式将它们合并回规范化状态。这样做的首选方法是什么?

原谅我的菜鸟,谢谢你的时间。

// normalized state
{
  "entities": {
    "items": {
      "1": {
        "id": 1,
        "title": "Item 1",
      },
      "2": {
        "id": 2,
        "title": "Item 2",
      },
      "3": {
        "id": 3,
        "title": "Item 3",
      },
    },
    "groups": {
      "20": {
        "id": 20,
        "title": "Group 1",
        "items": [ 1, 2 ]
      },
      "21": {
        "id": 21,
        "title": "Group 2",
        "items": [ 3 ]
      }
    }
  },
  "result": [ 20, 21 ]
}

// actions
export const addItem = values => ({
    type: ADD_ITEM,
    payload: {...values, itemID: uuid.v1() }
    // values come from a form
})

// reducer
const items = (state, action) => {
    switch(action.type) {
        case ADD_ITEM:
            let { items } = state.entities;
            let { itemID } = action.payload;

            return {
                ...items,
                [itemID]: {
                    id: itemID,
                    ...item,
                    subItems:[]
                }
            }
        default:
            return state;
    }
}
const groups = (state = initialState, action) => {
    switch(action.type) {
        case ADD_ITEM:
            let { payload } = action;
            let { groupID, itemID } = payload; // GroupID comes from form submit
            let { groups } = state.entities;

            return {
                ...groups,
                [groupID]: [
                    ...groups[groupID],
                    groups[groupID].items = [
                        ...groups[groupID].items,
                        itemID
                    ]
                ]
            }
        default:
            return state;
    }
}

export default groups;
4

1 回答 1

-1

您必须使用 combine reducer 将所有这些实体连接到一个状态。代码如下:

import user from './user';
import contacts from './contacts';
import activeUser from './activeUser';
import messages from './messages';
import {combineReducers} from 'redux';
import typing from './typing';


export default combineReducers({
    user,
    contacts,
    activeUser,
    messages,
    typing
});

在此处查看完整代码

于 2019-05-02T06:56:02.210 回答