javascript - 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 函数中添加另一个检查,但这似乎不起作用。关于我应该如何做这件事的任何想法?
解决方案
问题是输入表单无权访问列表进行任何比较。您可以通过将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
也很好。你可以随心所欲地进行比较。
推荐阅读
- amazon-web-services - 如何在 AWS API 网关映射模板中创建字符串化 json
- python - python-can J1939过滤掩码
- reactjs - 我在这种类型检查中做错了什么?
- sql - 在 SQL 中,我怎样才能只获得每组的第一个结果
- c# - Xamarin Android 应用程序不再被 Firebase 正确验证,因为在另一部手机上使用了手机 #
- react-native - fontFamily FontAwesome 不是系统字体,没有通过 Font.loadAsync 加载
- python - 根据用户输入检查 Python 列表/字典并从另一个列表中的相同索引值显示
- android - 我的应用程序如何在两个模拟器上运行发送/接收 SMS DATA 消息
- android - Android Kotin:要求用户将应用设置为默认短信处理程序不起作用
- android - 在 FragmentContainerView 中使用带有 XML 属性的 SupportMapFragment