【发布时间】: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: [] }?