繁体   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