2017-02-09 54 views
1

我在构造函数中的状态数组:如何在一个特定的索引更新阵列阵营JS

constructor(props) { 
    super(props); 
    this.state = {myarray: []}; 
} 

现在我想更新在特定的下标阵列。

this.setState({myarray[i]: 'test'}); 

给我一个unexpected token错误,在开幕支架[

什么是这样做的正确方法指点?

P.S.数组被动态地填充使用push方法才把我试图更新

回答

3

创建数组的副本:

const newArray = Array.from(this.state.myarray); 

更新索引:

newArray[i] = 'test'; 

和更新状态

this.setState({myarray: newArray}); 

您还可以使用immutable helpersused to be part of React's addons)更简洁地完成此操作。