首页 > 解决方案 > 为什么该项目在计数中没有得到总和?

问题描述

我正在尝试运行此代码以检查购物车中是否已经有产品,如果该产品已经存在,请将其添加到计数中。否则,将该项目添加到项目数组中,这是我存储所有正在添加的项目的地方。但是,只要一个项目已经存在,计数就不会加起来,而是一直返回 0。为什么会这样呢?

当我控制台记录它以调试它时,它只是打印count: NaN

这是我的 JS 代码:

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

       const exists = item.findIndex((i) => i.img  === product.img) > -1;

       if (exists) {
            item.count += 1
         console.log(item)
       }  else if (product.id === productsId) {
          setItem(item.concat(product))
        }
      })
  }

    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.count 是未定义的。item 是一个对象数组。你的速记item.count += 1确实,item.count = item.count +1; undefined + 1 是 NaN 所以 item.count 是 NaN。

同样,如果使用setItem条件,您不会首先更新状态,您正在改变不推荐的状态,并且反应甚至不会检测到更改,因此不会重新渲染。

您可以创建数组的副本,这样您就有了新的参考。然后更新您的特定对象属性。

let findInd = item.findIndex((i) => i.img  === product.img);
 const exists = (findInd > -1);

if (exists) {
          let newArry = [...item];
         let newObj = { ...newArry[findInd]};
newObj.count++;
         console.log(newArry)
  setItem(newArry);
       }

旁注:我希望你的任何 for 循环条件只被调用一次。我不认为将 setState 放在循环中是更新状态的安全方法。


推荐阅读