我正在尝试检查我的数组 data
中是否存在某个项目,如果存在,则阻止将其添加到数组中。
如果项已存在于数组中,handleCheck
函数将返回 true,但我不确定如何使用它来防止项被添加到数组中。
我试图在 handlePush
函数中使用它 this.handleCheck(item) == false ?
它应该检查它是否为假,如果是则推送,如果它返回 true 它应该说它存在但目前这不起作用,因为即使该项目存在它也会推送到数组并且它永远不会 console.log 'exists`
如何更改我的 handlePush 函数以使用 handleCheck 并防止再次添加数组中已存在的项目?
https://www.webpackbin.com/bins/-KpnhkEKCpjXU0XlNlVm
import React from 'react'
import styled from 'styled-components'
import update from 'immutability-helper'
const Wrap = styled.div`
height: auto;
background: papayawhip;
width: 200px;
margin-bottom:10px;
`
export default class Hello extends React.Component {
constructor() {
super()
this.state = {
data: []
}
this.handlePush = this.handlePush.bind(this)
this.handleRemove = this.handleRemove.bind(this)
this.handleCheck = this.handleCheck.bind(this)
}
handlePush(item) {
this.handleCheck(item) == false ?
this.setState({
data: update(this.state.data, {
$push: [
item
]
})
})
: 'console.log('exists')
}
handleRemove(index) {
this.setState({
data: update(this.state.data, {
$splice: [
[index,1]
]
})
})
}
handleCheck(val) {
return this.state.data.some(item => val === item.name);
}
render() {
return(
<div>
<button onClick={() => this.handlePush({name: 'item2'})}>push</button>
<button onClick={() => this.handlePush({name: 'item3'})}>push item3</button>
{this.state.data.length > 1 ? this.state.data.map(product =>
<Wrap onClick={this.handleRemove}>{product.name}</Wrap>) : 'unable to map' }
{console.log(this.state.data)}
{console.log(this.handleCheck('item2'))}
{console.log(this.handleCheck('item3'))}
</div>
)
}
}
最佳答案
应该是:
handleCheck(val) {
return this.state.data.some(item => val.name === item.name);
}
因为这里的 val
是一个对象而不是一个字符串。
关于javascript - 检查项目是否存在于数组 React 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45277306/