【发布时间】:2018-09-21 23:02:08
【问题描述】:
我将 react 与 redux 一起使用。
动作:
export const updateClicked = (id, section) => {
return {
type: actionTypes.UPDATE_CLICKED,
id,
section
};
};
请告知嵌套数组中不可变更新属性的最佳方法:
减速机:
const initialState = {
updates: {
html: {
id: 'html',
label: 'HTML',
count: 0,
items: [
{
id: 1,
label: 'Header',
price: 10,
bought: false
},
{
id: 2,
label: 'Sidebar',
price: 50,
bought: false
}
]
}
}
};
我的行动:
action = {
id: 1,
bought: true
}
我想更新 items 数组中的 bought 属性。即:
const updateClicked= (state, action) => {
const updateSections = state.updates[action.section].items;
const updatedItems = updateSections.map(el => {
if (el.id === action.id && !el.bought) {
el.bought = true;
}
return el;
});
//How to update state???
return {}
};
如果您能解释 2 种方法来做到这一点,我们会很高兴:
- 使用 es6 扩展运算符
- 使用一些库(如 immutability-helper)
谢谢!
【问题讨论】:
-
我知道这并不能回答您的问题。我稍后会谈到 :-) 但在我开始之前,我想建议您将商店的状态正常化。因为如果你保持 store 的状态正常化,编写 reducer 会容易得多,它的性能会好很多,如果你使用 memoized 选择器(即
reselect),你的应用程序的性能会好很多。长话短说:使用 redux 尽量保持商店的状态正常化。现在,我将继续回答您的问题... -
顺便说一句,那个动作的
type是什么动作? -
@Josep 我已经更新了代码
标签: redux react-redux immutability