反应添加数组到状态数组

时间:2020-01-22 05:27:59

标签: javascript reactjs

我是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时,列表中只有几个空数组([])

4 个答案:

答案 0 :(得分:1)

您可以将这样的数组添加到状态数组

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

要添加的功能

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

答案 1 :(得分:0)

更改为以下内容。

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)

答案 2 :(得分:0)

react中的深度克隆无法按您的方式进行。我更喜欢使用的一种方式是通过spread运算符。您可以执行以下操作:

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

希望这对您有用。

答案 3 :(得分:0)

做到这一点的最好方法是结构化。

let oldState = [1,2,4]

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