无法分配给只读属性 [英] Cannot assign to read only property

查看:73
本文介绍了无法分配给只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解为什么会收到错误消息:

I am having some trouble understanding why I am getting an error message:

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

TypeError: Cannot assign to read only property 'description' of object '#'

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

I know that the principle is that I don't want to modify state in my reducer. Instead, I want to return a new copy of the state.

这是我的减速器:

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 测试:

And here is my Reducer test:

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

However, I get the above error message. If I remove the deepFreeze the test passes. This means that I am somehow modifying the original state in some way but I can't figure out why especially because I created a new array of spreaded items.

任何帮助将不胜感激.

推荐答案

数组展开运算符制作了 state.items 数组的浅拷贝,但不制作其中的对象的拷贝那个数组.为了获得一个包含修改项目的新数组,您可以映射 state.items 并使用对象扩展运算符来更新项目:

The array spread operator makes a shallow copy of the state.items array, but does not make a copy of the objects inside of that array. In order to get a new array with modified items you can map over state.items and use the object spread operator to update the 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
        }
    }

这篇关于无法分配给只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆