簡體   English   中英

檢查數組 React 中是否存在項目

[英]Check if item exists in array React

我正在嘗試檢查數組data是否存在某個項目,如果存在,則阻止將其添加到數組中。

如果數組中已經存在一個項目, handleCheck函數將返回 true,但我不確定如何使用它來防止將項目添加到數組中。

我試圖在handlePush函數this.handleCheck(item) == false ?使用它this.handleCheck(item) == false ? 它應該檢查它是否是假的,如果是,然后推送,如果它返回真,它應該說它存在,但目前這不起作用,因為它會推送到數組,即使該項目存在並且它永遠不會 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是一個對象而不是一個字符串。

看看這個: https : //www.webpackbin.com/bins/-Kpo0Rk6Z8ysenWttr7q

在 React 中搜索數組中存在 Check value 時,我進入了這個頁面,並想為其他認為有任何特殊情況可以使用 React 檢查數組中的值的人提供一個解決方案(除了這個問題) .

您也可以正確地使用默認的 JavaScript 方法。 React 沒有什么特別之處。

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

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

謝謝。

在數組實例上使用includes()方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM