簡體   English   中英

反應將數組添加到狀態數組

[英]React add array to state array

我是 React 的新手。 在我的狀態下,我正在嘗試初始化一個空數組來存儲多邊形。

我想要的結構是這樣的數組this.state.polyList = [[dot1,dot2,dot3...],[dot1,dot2,dot3...]]

我想有一個

let newState = Object.assign({},this.state);
let newValue = [points]; // "points" is [dot1,dot2,dot3...]
console.log(newValue[0][0]); // able to print correctly
newState.polyList = newState.polyList.concat(newValue)
this.setState(newState)

但是,當我稍后記錄state.polyList ,列表中只有幾個空數組 ([])

您可以將這個數組添加到狀態數組

 state = {
    items: [4,5,6],
  };

添加功能

  handleClick = e => {
  this.setState({
   items:[...this.state.items,[Math.floor(Math.random()*100),7,8]]
   })
  };

更改為如下所示。

let newValue = [points]; // "points" is [dot1,dot2,dot3...]
console.log(newValue[0][0]); // able to print correctly

let newState = { ...this.state, 
                 polyList: [...this.state.polyList, newValue] };

this.setState(newState)

深克隆中react不工作,你正在做的方式。 我更喜歡使用的一種方法是通過spread運算符。 您可以執行以下操作:

let newState = [...this.state.polyList];
newState.push(points)
this.setState({ polyList: newState });

希望這對你有用。

最好的方法是構建。

let oldState = [1,2,4]

this.setState ([...oldState, [new state array]])

暫無
暫無

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

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