簡體   English   中英

無法分配給對象 &#39;# 的只讀屬性<Object> &#39;

[英]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
  )
}));

這樣,您只會讀取而不寫入您的狀態值。

無法分配給 object '# 的只讀屬性'property'<object> '<div id="text_translate"><p> 我有這個問題。</p><p> 帶接口:</p><pre> export interface IDevice { id: string, selected: boolean }</pre><p> 通過以下方式創建實例:</p><pre> let newDevice: IDevice = { id: uuid4(), selected: false, } as IDevice;</pre><p> 它被添加到 recoil state 中的數組中,並在 React 中用於 function 中,其中數組已使用 useRecoilState() 檢索。 const [leftList, setLeftList] = React.useState&lt;IDevice[]&gt;([]);</p><p> 現在它在處理程序中用於選擇列表控件上的設備,這里發生錯誤:</p><pre> ... leftList.map((item: IDevice) =&gt; { if (item.id === event.dataItem.id) { item.selected =.item;selected; } return item. })...</pre><p> 我收到錯誤消息:無法分配給 object '#' 的只讀屬性 'selected'</p><p> 即使首先通過 [...leftList] 克隆數組也無濟於事。</p><p> 我迷路了:-)希望有人能對此有所了解嗎?</p></div></object>

[英]Cannot assign to read only property 'property' of object '#<Object>'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 無法分配給 # 的只讀屬性“.js”<Object> 無法分配給 object 的只讀屬性“displayName” 無法分配給 object 的只讀屬性 無法分配給 object '[object Object]' 的只讀屬性 'name' Ngrx:無法分配給對象“[Object]”的只讀屬性“Property” 無法分配給 object '# 的只讀屬性'property'<object> '<div id="text_translate"><p> 我有這個問題。</p><p> 帶接口:</p><pre> export interface IDevice { id: string, selected: boolean }</pre><p> 通過以下方式創建實例:</p><pre> let newDevice: IDevice = { id: uuid4(), selected: false, } as IDevice;</pre><p> 它被添加到 recoil state 中的數組中,並在 React 中用於 function 中,其中數組已使用 useRecoilState() 檢索。 const [leftList, setLeftList] = React.useState&lt;IDevice[]&gt;([]);</p><p> 現在它在處理程序中用於選擇列表控件上的設備,這里發生錯誤:</p><pre> ... leftList.map((item: IDevice) =&gt; { if (item.id === event.dataItem.id) { item.selected =.item;selected; } return item. })...</pre><p> 我收到錯誤消息:無法分配給 object '#' 的只讀屬性 'selected'</p><p> 即使首先通過 [...leftList] 克隆數組也無濟於事。</p><p> 我迷路了:-)希望有人能對此有所了解嗎?</p></div></object> 未捕獲的TypeError:無法分配為只讀對象&#39;#的屬性&#39;background&#39; <Object> “ 未捕獲的TypeError:無法分配給對象'#<Object>'的只讀屬性'exports' TypeError:無法分配為只讀對象“#”的屬性“ exports” <Object> 在ReactJS中 無法分配給對象“#”的只讀屬性“exports”<Object> &#39;
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM