为什么这不向我的当前项目添加计数?

4jb9z9bj  于 2021-09-13  发布在  Java
关注(0)|答案(3)|浏览(299)

我正在尝试创建一个购物车,每当商品已经在购物车中,并且下次单击“添加到购物车”按钮时,商品的数量应该增加1。每次单击该按钮时,它都会将项目数量添加到购物车中。
我尝试通过查找项目的索引来执行此操作,如果它存在,则将项目的计数相加一。但这不起作用,因为这个数字没有得到汇总。

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

        let findInd = item.findIndex((i) => i.id  === product.id);
        const exists = (findInd > -1);
       // Part where it is supposed to add if the item is already in the cart
       if (exists) {
         let newArry = [...item];
        let newObj = { ...newArry[findInd]};
        newObj.counts += 1
         setItem(newArry);

       }  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(),
  img: steveJobs,
  homeImg: steveJobs,
  button: "add to cart",
  counts: 0
},
{
  id: uniqid(),
  img: diCaprio,
  homeImg: diCaprio,
  button: "add to cart",
  counts: 0
},
{
  id: uniqid(),
  img: lips,
  homeImg: lips,
  button: "add to cart",
  counts: 0
},
{
  id: uniqid(),
  img: buda,
  homeImg: buda,
  button: "add to cart",
  counts: 0
},
{
  id: uniqid(),
  img: spaceDog,
  button: "add to cart",
  counts: 0
},
{
  id: uniqid(),
  img:astroNube,
  button: "add to cart",
  counts: 0
},
{
  id: uniqid(),
  img: banksy,
  button: "add to cart",
  counts: 0
},
{
  id: uniqid(),
  img:banksyDJ,
  button: "add to cart",
  counts: 0
}
]

export default data;

以下是usecountscontext代码:

import { createContext } from 'react';

const useCountsContext = createContext();

export default useCountsContext;
jtw3ybtb

jtw3ybtb1#

你好像在变异 newObj.counts 在这里:

let newObj = { ...newArry[findInd]};
newObj.counts += 1

相反,请使用spread运算符更改 counts . 即

mutated = { ...newObj, counts: newObj.count += 1 };

话虽如此,你不需要 let newArry = [...item]; ,而不是使用 item.filter... 找到 newObj 你想采取行动。
然后,创建一个 newArry ,确保您添加 mutated 将其拆下,然后拆下 newObj . 不过,还是要确保不要直接变异对象。

byqmnocz

byqmnocz2#

你似乎很困惑 useContext()useState() . 我去掉了所有的上下文,用state替换了它。看看我做了什么,看看是否有意义。
在沙箱中运行代码

function Shop() {
  const [count, setCount] = useState(0)
  const [items, setItems] = useState([])

  const addCart = (productsId) => {
      setCount(count + 1)

      let findInd = items.findIndex((i) => i.id  === productsId);
      const exists = (findInd > -1);

      // Part where it is supposed to add if the item is already in the cart
      if (exists) {
        const newArry = items.map(x => (x.id===productsId) ? {...x, counts: x.counts + 1} : x)
        setItems(newArry);
      }
      else {
        const product = data.find(x => x.id === productsId);

        setItems([...items, {...product, counts: 1}])
      }
  }

    return (
        <div>
          <h1>Shop</h1>
          <div className="div___shop">
               <h3>Total count: {count}</h3>
              <div>
                <h3>Cart items:</h3>
                <div style={{margin: '10px'}}>
                  {items.map(x => (
                    <div>item {x.id} image: {x.img} count: {x.counts}</div>
                  ))}
                </div>
              </div>
              {data.map(({id, img, button}) => (
              <>

                <div key={id}>
                  {`id: ${id} img: ${img} `}
                  <button onClick={() => addCart(id)}>{button}</button>
                </div>
              </>
          ))}
          </div>
        </div>
    )
}
szqfcxe2

szqfcxe23#

您可以通过以下方法实现这一点:

data.forEach((product) => {
  let findInd = item.findIndex((i) => i.id  === product.id);
  const exists = (findInd > -1);

  if (exists) {
    const targetObject = item[findInd]
    targetObject.counts += 1

    const newItems = [
      ...item.slice(0, findInd),
      targetObject, 
      ...item.slice(findInd + 1)
    ]
    setItem(newItems);
  }

基本上,您可以使用更新的计数形成新数组,并通过将其传递给 setItem .
在本例中,您正在从数组中复制一个项 let newObj = { ...newArry[findInd]} ,将其递增1,但不更新 newArry 这就是为什么计数也没有更新。
更新:
我更新了您的代码,使其更具可读性,并修复了计数错误(foreach函数和productsid搜索中存在问题)。我还使用了usestate钩子而不是usecontext
我在codesandbox中复制了下面的代码-一切正常,按您的要求计算-codesandbox

const [count, setCount] = React.useState(0)
const [item, setItem] = React.useState([])

const addCart = (productsId) => {
  setCount(count + 1)
  const index = item.findIndex((e) => e.id  === productsId);
  if (index === -1) {
    const newArr = [...item].concat(data.filter((e) => e.id === productsId))
    setItem(newArr)
  } else {
    const targetObject = item[index]
    targetObject.counts += 1

    const newItems = [
      ...item.slice(0, index),
      targetObject, 
      ...item.slice(index + 1)
    ]
    setItem(newItems);
  }
}

相关问题