2017-09-14 30 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 
});