使用react增加电子商务中的商品功能



我正试图在我的电子商务项目中添加增加商品的功能,但当我增加一种产品的价值时,它会增加所有产品的价值,我该如何以不同的方式来处理它,使其以我希望的方式工作。(查看stackblitz链接以获取工作示例(。

import React, { useState } from 'react';
const products = [
{ id: 1, clothe: 'pant' },
{ id: 2, clothe: 'shirt' },
{ id: 3, clothe: 'coat' },
];
const Cart = () => {
const [itemCount, setItemCount] = useState(0);
const increaseItem = () => {
setItemCount(itemCount + 1);
};
const decreaseItem = () => {
setItemCount(itemCount - 1);
};
return (
<div>
{products.map((item) => (
<div>
<div> {item.clothe} </div>
<button onClick={() => increaseItem()}>+</button>
<span>{itemCount}</span>
<button onClick={() => decreaseItem()}>-</button>
</div>
))}
</div>
);
};
export default Cart;

工作链路,例如

您能为每种产品尝试这种单独维护的状态吗。

import React, { useState } from 'react';
const Cart = () => {
const [products, setProducts] = useState([
{ id: 1, clothe: 'pant', count: 0 },
{ id: 2, clothe: 'shirt', count: 0 },
{ id: 3, clothe: 'coat', count: 0 },
]);
const [itemCount, setItemCount] = useState(0);
const increaseItem = (index, currentCount) => {
let uProducts = [...products];
uProducts[index].count = currentCount + 1;
setProducts(uProducts);
};
const decreaseItem = (index, currentCount) => {
let uProducts = [...products];
uProducts[index].count = currentCount - 1;
setProducts(uProducts);
};
return (
<div>
{products.map((item, index) => (
<div>
<div> {item.clothe} </div>
<button onClick={(e) => increaseItem(index, item.count)}>+</button>
<span>{item.count}</span>
<button onClick={(e) => decreaseItem(index, item.count)}>-</button>
</div>
))}
</div>
);
};
export default Cart;

每个product的计数状态必须分开。

import React, { useState } from 'react';
const products = [
{ id: 1, clothe: 'pant' },
{ id: 2, clothe: 'shirt' },
{ id: 3, clothe: 'coat' },
];
const Cart = () => {
const [itemCount, setItemCount] = useState(products.map((item, index) => 0));
const increaseItem = (index) => {
const _itemCount = [...itemCount];
_itemCount[index]++;
setItemCount(_itemCount);
};
const decreaseItem = (index) => {
const _itemCount = [...itemCount];
_itemCount[index]--;
setItemCount(_itemCount);
};
return (
<div>
{products.map((item, index) => (
<div>
<div> {item.clothe} </div>
<button onClick={() => increaseItem(index)}>+</button>
<span>{itemCount[index]}</span>
<button onClick={() => decreaseItem(index)}>-</button>
</div>
))}
</div>
);
};
export default Cart;

工作代码

最新更新