我很难理解为什么我会收到错误信息:
TypeError:无法指定对象'#‘的只读属性'description’
我知道原理是,我不想修改我的减速器的状态。相反,我想返回状态的新副本。
这是我的减速机:
action TOGGLE_CHECKBOX:
{
let copyOfItems = [...state.items]; // create a new array of items
copyOfItems.forEach(i => i.description = "newDescription");
// return a new copy of the state
return {
...state,
items: copyOfItems
}
}这是我的减速器测试:
it ('Test that each item description is set', () => {
const state = {
items: [
{ description: "d1" },
{ description: "d2" }
]
}
deepFreeze(state);
expect(MyReducer(state, { type: TOGGLE_CHECKBOX })).toEqual({
items: [
{ description: "newDescription" },
{ description: "newDescription" }
]
});
});但是,我得到了上面的错误消息。如果我删除deepFreeze,测试就通过了。这意味着我正在以某种方式修改原始状态,但我不知道为什么,特别是因为我创建了一个新的扩展项数组。
任何帮助都将不胜感激。
发布于 2019-09-05 19:52:54
数组扩展运算符对state.items数组进行浅层复制,但不会复制该数组中的对象。为了获得一个带有修改项的新数组,您可以在state.items上映射并使用对象扩展操作符来更新项:
action TOGGLE_CHECKBOX:
{
const copyOfItems = state.items.map(
i => ({...i, description: 'newDescription'})
); // create a new array of items with updated descriptions
// return a new copy of the state
return {
...state,
items: copyOfItems
}
}发布于 2019-09-05 20:01:58
扩展运算符对数组进行浅拷贝,这意味着数组中的对象仍将保留对原始值的引用。您需要为每个对象创建一个新的副本,然后像下面这样更新每个对象的描述
let copyOfItems = state.items.map( obj => ({
...obj,
description: "newDescription"
}));
return {
...state,
items: copyOfItems
}希望这能帮上忙!
https://stackoverflow.com/questions/57812091
复制相似问题