首页 > 解决方案 > React - 检查数组中是否已经存在一个值?

问题描述

我正在制作一个简单的 React 购物清单,您可以在其中添加/删除列表中的项目(此处为 pen)。到目前为止它工作得很好,除非你在列表中添加一个重复的条目并尝试删除它,它会变得混乱(它使用值作为键,所以大概这就是原因)。为了解决这个问题,我想在添加项目时检查该值是否已存在于列表数组中,并阻止它被添加。我尝试通过将 this: 更改if (this.state.newItem.length > 0){为 this: if (this.state.newItem.length > 0 && this.state.items.includes(this.state.newItem) == false){(第 18 行)在 handleAddNew 函数中添加另一个检查,但这似乎不起作用。关于我应该如何做这件事的任何想法?

标签: javascriptarraysreactjslistarraylist

解决方案


问题是输入表单无权访问列表进行任何比较。您可以通过将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也很好。你可以随心所欲地进行比较。


推荐阅读