首页 > 解决方案 > 您如何检查数组中是否存在相同的项目并执行其他操作?

问题描述

我正在尝试将项目推送到数组中,但我希望如果数组中有类似的项目,只需将计数更新为 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

解决方案


item是一个产品列表(数组)并且product是一个对象。您不能includes在包含对象的数组上使用,您可以使用通用for循环forEach、 或现代find在您的 items 数组中搜索产品

const addCart = (productsId) => {
    setCount(count + 1)
    data.forEach((product) => {
        const exists = item.findIndex((i) => i.id === product.id) > -1;
        // if check is on title
        // const exists = item.findIndex((i) => i.title === product.title) > -1;
        if (exists) {
            product.count += 1
        } else if (product.id === productsId) {
            setItem(item.concat(product))
        }
    })
}

OP评论后更新

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)
      // grab the product object from data array
      const product = data.find((d) => d.id === productsId);
      // if product is not found
      if (product == null) {
          throw new Error("Invalid ProductId");
      }
      // check if product already exists in item list
      // grab the index of the product in the item list
      const exists = item.findIndex((i) => i.id === product.id);
      // if index is -1, the product doesn't exists
      if (exists === -1) {
        // add to item array
        setItem(item.concat(product));
      } else {
        // product already exists
        // increase the count
        const cart = [...item]; // create a Shallow copy of cart
        cart[exists].count += 1; // increment the count
        setItem(cart); // update the cart state
      }
  }

    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

推荐阅读