簡體   English   中英

使用SetState在react中更新數組對象中的一項

[英]Use SetState to update one of the item in array object in react

我有一個稱為項目的狀態對象。

items: [
    {
      name: 'John'
      id: '1',
      checked: false,
    },
    {
      name: 'Dude'
      id: '2',
      checked: true,
    }
]

在UI上,單擊“我需要將id = 1的項目的選中屬性更新為true”如何將setState用於項目以更新項目中的一個(單個)項目

像這樣嗎 注釋中的解釋:

onClick(id) {
  // Create a temporary copy of your items array
  const itemsCopy = this.state.items.slice();

  // Find the index of the items where the item has the id you want
  const idx= itemsCopy.findIndex(x => x.id === id);

  // Re-assign the item to have the same values as before (name and id), but change the checked to true
  itemsCopy[idx] = {...itemsCopy[idx], checked: true};

  // Update the state with our modified copy
  this.setState({items: itemsCopy});
}
const {items} = this.state;
const index = items.findIndex(val=>val.id ===1);
items[index].checked = true;
this.setState({items});

狀態中的“ items”對象應更新。 因此slice可用於復制數組。 並且將其設置回狀態應該足夠了,以便組件可以了解狀態已更改。

let items = this.state.items.slice();

const index = items.findIndex(val => val.id === 1);
items[index].checked = true;
this.setState({ items });

暫無
暫無

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

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