首页 > 解决方案 > 如何检查数组中是否存在现有值,如果存在则不再次添加?

问题描述

我正在尝试将项目推送到数组中,但我希望如果数组中有类似的项目,只需将计数更新为 1,而不是再次在数组中添加该项目。我已经尝试了很多东西,例如该include()功能,但它没有按预期工作,因为当我item.includes(product)映射每个产品时,每当我添加一个项目时,每个产品的计数都会更新......

import React, {useState, useContext} from 'react'
import data from './data.js'
import useCountsContext from './context/useCountsContext.js'
var uniqid = require('uniqid');

function Shop({ data }) {
  const {count, setCount} = useContext(useCountsContext)
  const {item, setItem} = useContext(useCountsContext)

  const addCart = (productsId) => {
      setCount(count + 1)
      data.forEach((product) => {
       if (item.includes(product)) {
         product.count += 1
       }  else if (product.id === productsId) {
          setItem(item.concat(product))
        }
      })
  }
console.log(item)

    return (
        <div>
          <h1>Shop</h1>
          <div className="div___shop">
          {data.map(({id, img, button}) => (
            <>
              <img className="img___shop" key={id} src={img}></img>
              <div key={id}>
                <button onClick={() => addCart(id)}>{button}</button>
              </div>
            </>
          ))}
          </div>
        </div>
    )
}

export default Shop

我的数据文件:

import diCaprio from './img/diCaprio.jpg'
import steveJobs from './img/steveJobs.jpg'
import lips from './img/lips.jpg'
import buda from './img/buda.jpg'
import spaceDog from './img/spaceDog.jpg'
import astroNube from './img/astroNube.jpg'
import banksy from './img/Banksy.jpg'
import banksyDJ from './img/banksyDJ.jpg'
var uniqid = require('uniqid');


const data = [{
  id: uniqid(),
  title: "Steve Jobs",
  img: steveJobs,
  homeImg: steveJobs,
  button: "add to cart",
  count: 0
},
{
  id: uniqid(),
  img: diCaprio,
  homeImg: diCaprio,
  button: "add to cart",
  count: 0
},
{
  id: uniqid(),
  img: lips,
  homeImg: lips,
  button: "add to cart",
  count: 0
},
{
  id: uniqid(),
  img: buda,
  homeImg: buda,
  button: "add to cart",
  count: 0
},
{
  id: uniqid(),
  img: spaceDog,
  button: "add to cart",
  count: 0
},
{
  id: uniqid(),
  img:astroNube,
  button: "add to cart",
  count: 0
},
{
  id: uniqid(),
  img: banksy,
  button: "add to cart",
  count: 0
},
{
  id: uniqid(),
  img:banksyDJ,
  button: "add to cart",
  count: 0
}
]

export default data;

标签: javascriptreactjs

解决方案


includes不适用于对象。尝试findfindIndex代替。我也认为你的检查是错误的。您需要检查是否items已选择productId,如果是,则更新其计数。

 const addCart = (productsId) => {
      setCount(count + 1)
      data.forEach((product) => {
       let index = items.findIndex(itm => itm.id === product.id && productId === product.id)
       
       if (index >= 0) {
         let newProduct = { ...items[index] }
         newProduct.count += 1
         setItem( [...item, [index]: newProduct ])
       } else {
          setItem(item.concat(product))
        }
      })
  }

推荐阅读