我正在尝试创建一个购物车,每当商品已经在购物车中,并且下次单击“添加到购物车”按钮时,商品的数量应该增加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;
3条答案
按热度按时间jtw3ybtb1#
你好像在变异
newObj.counts
在这里:相反,请使用spread运算符更改
counts
. 即话虽如此,你不需要
let newArry = [...item];
,而不是使用item.filter...
找到newObj
你想采取行动。然后,创建一个
newArry
,确保您添加mutated
将其拆下,然后拆下newObj
. 不过,还是要确保不要直接变异对象。byqmnocz2#
你似乎很困惑
useContext()
及useState()
. 我去掉了所有的上下文,用state替换了它。看看我做了什么,看看是否有意义。在沙箱中运行代码
szqfcxe23#
您可以通过以下方法实现这一点:
基本上,您可以使用更新的计数形成新数组,并通过将其传递给
setItem
.在本例中,您正在从数组中复制一个项
let newObj = { ...newArry[findInd]}
,将其递增1,但不更新newArry
这就是为什么计数也没有更新。更新:
我更新了您的代码,使其更具可读性,并修复了计数错误(foreach函数和productsid搜索中存在问题)。我还使用了usestate钩子而不是usecontext
我在codesandbox中复制了下面的代码-一切正常,按您的要求计算-codesandbox