简体   繁体   English

在 reactJs 中使用 useState 更改嵌套对象中的值

[英]Change a value in a nested object using useState in reactJs

I'm trying to change the value of an object property nested in an array nested inside an object using useState.我正在尝试使用 useState 更改嵌套在嵌套在对象内的数组中的对象属性的值。

State is set as follows:状态设置如下:

  const [groupState, setGroupState] = useState({
    groupId: uuidv4(),
    content: [{ rowId: uuidv4(), field: '', from: '', to: '' }],
  });

I'm trying to change the value of the 'field' property.我正在尝试更改“字段”属性的值。 If I add an entire 'dummy' object with the required value in the required property then it works:如果我在 required 属性中添加具有所需值的整个“虚拟”对象,则它可以工作:

setGroupState({
  ...groupState,
  content: groupState.content.map((item) => {
    if (item.rowId === rowId) {
      return (item = { rowId: uuidv4(), field: value, from: '', to: '' });
    }
  }),
});

However, I need to just update the specific property value, not the whole object.但是,我只需要更新特定的属性值,而不是整个对象。 My latest effort is the following:我最近的努力如下:

setGroupState({
  ...groupState,
  content: groupState.content.map((item) => {
    if (item.rowId === rowId) {
      return (item.field = value);
    }
  }),
});

Which returns the error: "Cannot create property 'field' on string 'user'" - I'm doing somethign wrong but I can't work out what.它返回错误:“无法在字符串 'user' 上创建属性 'field'” - 我做错了,但我不知道是什么。

Try destructing your item object:尝试销毁您的 item 对象:

setGroupState({
  ...groupState,
  content: groupState.content.map((item) => ({
    ...item,
    field: item.rowId === rowId ? value : item.field,
  })),
});

// Without explicit return
setGroupState({
  ...groupState,
  content: groupState.content.map((item) => {
    return { ...item, field: item.rowId === rowId ? value : item.field };
  }),
});

Okay, got it, thanks Dennis Vash - just needed a little change:好的,明白了,谢谢丹尼斯·瓦什 - 只需要一点点改变:

setGroupState({
  ...groupState,
  content: groupState.content.map((item) => ({
    ...item,
    field: item.rowId === rowId ? value : item.field,
  })),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM