无法分配给只读属性

IT技术 javascript reactjs redux
2021-05-22 06:24:26

我在理解为什么收到错误消息时遇到了一些麻烦:

类型错误:无法分配给对象“#”的只读属性“描述”

我知道原则是我不想在我的减速器中修改状态。相反,我想返回状态的新副本。

这是我的减速机:

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
        }
    }

这是我的 Reducer 测试:

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测试通过。这意味着我以某种方式以某种方式修改了原始状态,但我无法弄清楚原因,尤其是因为我创建了一个新的展开项目数组。

任何帮助将不胜感激。

2个回答

数组展开运算符创建数组的浅表副本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
        }
    }

展开运算符对数组进行浅拷贝,这意味着数组内的对象仍将保留对原始值的引用。您需要为每个对象制作一个新副本,然后像这样更新每个对象的描述

let copyOfItems = state.items.map( obj => ({
  ...obj,
  description: "newDescription"
})); 

return {
  ...state,
  items: copyOfItems
}

希望这可以帮助 !