簡體   English   中英

在反應中使用 setState 將預定義的對象推送到數組中

[英]Push predefined objects into array using setState in react

如何使用擴展運算符/ES6 實現這一點?

我想遍歷我的數據並用一個對象數組填充我的狀態,其中對象包含兩個鍵/值對。 我希望它像...

this.state = {
data: [ {indexNumber: 1, show: false}, {indexNumber: 2, show: false}, {indexNumber: 3, show: false} ]

我的[變異]版本;

this.state = { data: []}

data.map((element, index) => {
    this.state.data.push({ indexNumber: index, show: false}] })
});

您不能修改狀態對象。 您必須調用 setState 並使用新值:

this.setState({data: [...this.state.data, {indexNumber: index, show: false}]})

暫無
暫無

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

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