2017-09-14 33 views
0

我對React非常陌生,我試圖構建經典的待辦事項列表!不過,我正在努力追蹤數組項目。
我創建的項目如下:添加到React中的數組

 this.setState({item: { 
     text: event.target.value, 
     index: this.state.items.length++, 
     completed:false 
     } 

我一直在增加項目的數組是這樣的:

 this.setState({items:this.state.items.concat(this.state.item)}); 

但這種方法創建一個新的數組每一次,所以我無法使用該項目的索引。但是,當我嘗試使用push來添加到數組中時,我似乎無法顯示它!任何幫助將非常感激!

+0

當您使用'push'時,您使用了哪些代碼?或者 - 你可以在每個項目上放置一個ID,所以你不需要位置索引? –

+0

推動將改變原始數組,不返回它 – AHB

+1

你的意思是「_我無法使用item_的索引」 –

回答

1

我在這裏懷疑的是當發生添加任務的事件時,您試圖設置item的狀態,然後立即設置items狀態。

陣營5批次多的setState()調用到性能更新一次。」

請參閱docs。所以,你不應該指望item當您嘗試this.setState({items:this.state.items.concat(this.state.item)});有你的最新項目

你可以試試下面的

const item = [{ 
    text: event.target.value, 
    index: this.state.items.length + 1, 
    completed:false 
}] 

let items = {this.state} 
items = items.push(item) 
this.setState({items}) 

你也可以將函數傳遞給setState方法

this.setState(function(prevState, props) { 
    //Code goes here 
});