簡體   English   中英

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

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

我正在嘗試使用 useState 更改嵌套在嵌套在對象內的數組中的對象屬性的值。

狀態設置如下:

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

我正在嘗試更改“字段”屬性的值。 如果我在 required 屬性中添加具有所需值的整個“虛擬”對象,則它可以工作:

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

但是,我只需要更新特定的屬性值,而不是整個對象。 我最近的努力如下:

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

它返回錯誤:“無法在字符串 'user' 上創建屬性 'field'” - 我做錯了,但我不知道是什么。

嘗試銷毀您的 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 };
  }),
});

好的,明白了,謝謝丹尼斯·瓦什 - 只需要一點點改變:

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