2017-02-09 20 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)更簡潔地完成此操作。