反应-检查数组中是否已存在值?

时间:2019-04-01 12:35:17

标签: javascript arrays reactjs list arraylist

我最近一直在学习React,并且正在开发一个简单的购物清单程序,您可以在其中添加/删除清单(pen here)中的商品。到目前为止,它工作得很好,除非您将重复条目添加到列表中并尝试将其删除,否则会感到困惑(它使用值作为键,因此大概就是这个原因)。为了解决这个问题,我想在添加项目时检查列表数组中是否已经存在该值,并防止添加它。我尝试通过将以下内容从if (this.state.newItem.length > 0){更改为if (this.state.newItem.length > 0 && this.state.items.includes(this.state.newItem) == false){(第18行),在handleAddNew函数中添加另一项检查,但这似乎不起作用。关于如何执行此操作的任何想法?

1 个答案:

答案 0 :(得分:2)

问题在于报名表无权访问列表以进行任何比较。您可以将addItem函数更改为:

addItem(item) {
  // only add if the item doesn't exist in the list
  if(this.state.items.indexOf(item) < 0){
    this.setState((state) => ({
      items: state.items.concat([item])
    }))
  }
}

请注意,我在这里使用indexOf,但也可以使用includes。您可以根据自己的喜好进行比较。

相关问题