[英]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.