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

AT9*_*T92 1 javascript arrays list arraylist reactjs

我正在处理一个简单的 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 函数中添加另一个检查,但这似乎不起作用。关于我应该如何去做的任何想法?

Mat*_*Way 6

问题是条目表单无权访问列表以进行任何比较。您可以通过将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])
    }))
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,我indexOf在这里使用,但includes也很好。您可以随意进行比较。