簡體   English   中英

使用 useState-hook 更改 React 中的對象數組,無需深度復制

[英]Alter Object Array in React with useState-hook without deep copying

改變對象數組的最佳和干凈的方法是什么?

我有一個看起來像這樣的代碼。

const [get_post, set_post] = useState([
    {name: "First"},
    {name: "Second"},
    {name: "Third"},
  ])

我想在某個索引上添加和編輯鍵。 所以我這樣做:

 <button onClick={()=>
    set_post([...get_post, get_post[0].content = "This is index zero" ])
 }> Manipulate! </button>

我的結果是這樣的:

[
    {"name": "First", "content": "This is index zero"},
    {"name": "Second"},
    {"name": "Third"},
    "This is index zero" <-- This line is the problem
]

我在谷歌上搜索了很多,但這似乎是一個常見的主題。

這篇文章用鍵控對象描述了相同的問題和解決方案,這對我沒有幫助。
React Hooks useState() 與 Object

這篇文章支持 3rd 方庫和/或深度復制,我懷疑這也不是“正確”的做法。
在 ReactJS 中更新數組中的對象的最佳方法是什么?

這個線程還支持很多深拷貝和映射,我想我不需要(它是一個數組,我應該能夠通過索引來尋址我的對象)?
如何在 React Hooks 的對象數組中更新狀態`onChange`

另一種深拷貝解決方案
https://codereview.stackexchange.com/questions/249405/react-hooks-update-array-of-object

名單還在繼續……

基本上我想要沒有多余線條的結果,

如果可能的話:

  • 無需深度復制要重新注入的狀態。
  • 沒有第 3 方庫。
  • 不使用鍵控對象。
  • 無需在 set_post 中運行地圖/過濾器循環。

編輯:為什么在 setPost 中不需要 map 的原因。

在我的特定場景中,呈現 getPost 的模塊已經是一個地圖循環。 試圖避免嵌套循環。

(我的邏輯簡化了)

const [get_post, set_post] = useState([
    {name: "First"},
    {name: "Second"},
    {name: "Third"},
  ])

//Render module
//Fixed numbers of controllers for each Object in Array.

get_post.map((post, index)=> {
<>

  <button onClick={()=>
     set_post([...get_post, get_post[index].content = "Content 1" ])}
     }> 
     Controller 1
  </button>

  <button onClick={()=>
     set_post([...get_post, get_post[index].content = "Content 2" ])}
     }> 
     Controller 2
  </button>

  <button onClick={()=>
     set_post([...get_post, get_post[index].content = "Content 3" ])}
     }> 
     Controller 3
  </button>

//...

</>
})

如果您只想更改第一個屬性,請先從數組中提取它。

您可以使用功能更新方法訪問當前狀態值並返回一個包含您想要的更改的新值。

set_post(([ first, ...others ]) => [{
  ...first,
  content: "This is index zero"
}, ...others])

要更改任何特定索引,您可以將當前數組映射到一個新數組,在到達時為目標索引創建一個新對象

let x = the_target_index

set_post(posts => posts.map((post, i) => i === x ? {
  ...post,
  content: `This is index ${x}`
} : post))

我找到了一個有效的解決方案!
我還沒有在其他地方看到過這個帖子,所以研究一下可能很有趣。

要按索引更改或向數組中的對象添加鍵/值,只需執行以下操作:

    <button onClick={() => {
      set_modules( [...get_modules , get_modules[index].content = "my content" ] )
      set_modules( [...get_modules ] ) //<-- this line removes the last input
    }
      }>

正如 Phil 所寫,較早的代碼被解釋為:

const val = "This is index zero"; 
get_post[0].content = val; 
get_post.push(val);

這似乎刪除了最新的get_post.push(val)

有人可以解釋為什么會這樣嗎?

暫無
暫無

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM