[英]Cannot assign to read only property of object '#<Object>'
我正在尝试创建一个重复的数组,这样我就可以编辑值并将其设置回来,这就是我得到的:
const handleInput: any = (index: any, property: any, value: any) => {
const newCertificates = [...props.resume.certifications];
newCertificates[index][property] = value;
props.setResume({ ...props.resume, certifications: newCertificates })
}
但我得到这个错误:
Certificates.tsx:18 Uncaught TypeError: Cannot assign to read only property 'certificationName' of object '#<Object>'
您正在尝试直接修改您的状态,因为newCertificates
中的对象仍然是它们在原始状态中引用的相同对象。 使用[...]
只会创建数组的浅表副本,因此不会克隆其中的对象(有关详细信息,请参见此处)。 在 React 上,你不应该直接修改状态,因为这会导致重新渲染出现问题,这就是 TS 试图告诉你的错误。
不要修改这些对象,而是在props.resume.certifications
上使用.map()
,然后在找到需要修改的对象后返回一个新对象,并返回一个具有更新值的新对象:
props.setResume(resume => ({
...resume,
certifications: resume.certifications.map((obj, i) =>
i === index ? {...obj, [property]: value} : obj
)
}));
这样,您只会读取而不写入您的状态值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.