【问题标题】:How to merge updates into normalized redux state如何将更新合并到规范化的 redux 状态
【发布时间】:2017-06-14 07:39:00
【问题描述】:

我刚开始使用 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;

【问题讨论】:

  • 你看过 normalizr 提供的 redux 例子吗? github.com/paularmstrong/normalizr/tree/master/examples/redux/… 每个用例都会有所不同,因此很难给出直接的答案。
  • @PaulArmstrong 我有,但我不明白如何扩展它以进行 CRUD 类型的操作。我想我无法理解的是:每个减速器都作用于实体中的一个对象。完成所有归约后,我们如何将这些对象合并回规范化状态 {entities: ..., result: [] }?

标签: redux normalizr


【解决方案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
});

查看完整代码here

【讨论】:

    猜你喜欢
    • 2016-10-28
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2020-02-04
    相关资源
    最近更新 更多