【发布时间】:2018-10-25 14:01:17
【问题描述】:
我正在寻找将新项目对象添加到减速器中的类别。 reducer 接收一个类别索引和一个新的 item 对象。
有谁知道用这种数据结构不可变地更新状态的最佳方法:
const initialState = {
categories: [
{
id: 1,
name: "vegetables",
items: [
{name: "potatoes", id: Math.floor(Math.random() * 99999)},
{name: "carrots", id: Math.floor(Math.random() * 99999)}
]
},
{
id: 2,
name: "dairy",
items: [
{name: "milk", id: Math.floor(Math.random() * 99999)},
{name: "cheese", id: Math.floor(Math.random() * 99999)}
]
},
{
id: 3,
name: "meat",
items: [
{name: "chicken", id: Math.floor(Math.random() * 99999)}
]
}
]
}
还是最好使用外部包,比如 immutable.js?
stackoverflow 上还有许多其他类似的问题,但没有一个具有相同的结构。
更新
reducer 的其余部分如下所示:
const shoppingItemsReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_SHOPPING_ITEM:
const categories = [...state.categories];
categories[action.selectedCategoryIndex].items.push(action.newItemObj);
return {
...state,
categories
}
default:
return state
}
}
使用push 工作正常,但它正在改变状态
【问题讨论】:
-
你的减速器是什么样子的?
-
更新问题
-
如果将其分配给新的 var 并执行 concat 以防止突变,则不要推送。 :)
标签: javascript redux react-redux