无法分配给只读属性

nob*_*are 1 javascript reactjs redux

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

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

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

这是我的减速器:

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
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的 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" }
        ]
    });
});
Run Code Online (Sandbox Code Playgroud)

但是,我收到上述错误消息。如果我删除deepFreeze测试通过。这意味着我以某种方式以某种方式修改了原始状态,但我无法弄清楚原因,特别是因为我创建了一个新的展开项目数组。

任何帮助将不胜感激。

azu*_*ndo 7

数组展开运算符创建数组的浅表副本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
        }
    }
Run Code Online (Sandbox Code Playgroud)