我正在制作一个简单的 React 购物 list ,您可以在其中添加/删除列表中的项目 ( pen here )。到目前为止,它工作得很好,除非您向列表添加重复的条目并尝试删除它,它会变得困惑(它使用值作为键,所以大概这就是原因)。为了解决这个问题,我想在添加项目时检查列表数组中是否已存在该值,并阻止添加它。我尝试在handleAddNew函数中添加另一个检查,方法是将: if (this.state.newItem.length > 0){
更改为: if (this.state.newItem.length > 0 && this.state.items.includes(this.state.newItem) == false){
(第 18 行),但这似乎不起作用。关于我应该如何去做这件事有什么想法吗?
最佳答案
问题是报名表无法访问列表来进行任何比较。您可以通过将 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
也可以。您可以随心所欲地进行比较。
关于javascript - React - 检查数组中是否已存在某个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55455271/