[英]Cannot assign to read only property of object '#<Object>'
I'm trying to create a duplicate array so I can edit the values and set it back also, here is what I got:我正在尝试创建一个重复的数组,这样我就可以编辑值并将其设置回来,这就是我得到的:
const handleInput: any = (index: any, property: any, value: any) => {
const newCertificates = [...props.resume.certifications];
newCertificates[index][property] = value;
props.setResume({ ...props.resume, certifications: newCertificates })
}
But I get this error:但我得到这个错误:
Certificates.tsx:18 Uncaught TypeError: Cannot assign to read only property 'certificationName' of object '#<Object>'
You're trying to modify your state directly, as the objects within newCertificates
are still the same objects that they referred to in your original state.您正在尝试直接修改您的状态,因为
newCertificates
中的对象仍然是它们在原始状态中引用的相同对象。 Using [...]
only creates a shallow copy of your array, so the objects within are not cloned (see here for more details).使用
[...]
只会创建数组的浅表副本,因此不会克隆其中的对象(有关详细信息,请参见此处)。 On React, you shouldn't modify state directly as that can lead to issues with re-rendering, and that is what TS is trying to tell you with the error.在 React 上,你不应该直接修改状态,因为这会导致重新渲染出现问题,这就是 TS 试图告诉你的错误。
Rather than modifying these objects, use .map()
on props.resume.certifications
and then return a new object once you find the object that you need to modify and return a new object with the updated value:不要修改这些对象,而是在
props.resume.certifications
上使用.map()
,然后在找到需要修改的对象后返回一个新对象,并返回一个具有更新值的新对象:
props.setResume(resume => ({
...resume,
certifications: resume.certifications.map((obj, i) =>
i === index ? {...obj, [property]: value} : obj
)
}));
This way, you're only reading and never writing to your state value.这样,您只会读取而不写入您的状态值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.