简体   繁体   中英

Check if item exists in array React

I'm trying to check if an item exists in my array data and if it does then prevent it from being added to the array.

The handleCheck function will return true if an items already exists in the array but I'm not sure how to then use this to prevent the item from being added to the array.

I have attempted to use it in the handlePush function this.handleCheck(item) == false ? it should check if it's false and if so then push, if it returns true it should say it exists but at the moment this is not working as it will push to the array even if the item exists and it will never console.log 'exists`

How can I change my handlePush function to use handleCheck and prevent an item that already exists in the array to be added again?

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>
    )

  }
}

it should be:

handleCheck(val) {
    return this.state.data.some(item => val.name === item.name);
}

because val here is an Object not a String.

Check this out: https://www.webpackbin.com/bins/-Kpo0Rk6Z8ysenWttr7q

While searching for Check value exists in an array in React , I was landed in this page and would like to give a solution (apart from this question) for others who think there is any special case to check for a value in an array using React.

You can rightly use the default JavaScript method too. There is nothing special when it comes to React.

var arr = ["steve", "bob", "john"];

console.log(arr.indexOf("bob") > -1); //true

Thank you.

Use the includes() method on the array instance.

 console.log(['red', 'green'].includes('red')) console.log(['red', 'green'].includes('blue'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM