我正在做出反应和编程本身的第一步,为此我制作了一个简单的购物车,它允许我将要购买的产品添加到以空数组开头的 useState .我也有另一个 useState 中的产品。当我通过具有 addProduct 功能的按钮添加产品时,它会验证该产品是否已在列表中,如果是,则在未添加的情况下增加数量。问题是,当产品已经存在时,它会很好地增加数量,但它也会在处于另一个 useState 的产品中实现。由此,我采用了 chrome 组件的扩展,因为当我从购物清单中删除产品并将其放回原处时,它会将其添加到我身上,但这次使用的是上次的数量。
import React, { useState } from "react";
import { AvailableProductsList } from "./components/AvailableProductsList";
import { ShoppingListCart } from "./components/ShoppingListCart";
export const App = () => {
// useState that has the products available
const [products, setProducts] = useState([
{ id: 1, name: "Apple", description: "Apple x 6", amount: 1, price: 3000 },
{ id: 2, name: "Rice", description: "Rice x 1 lb", amount: 1, price: 4000 },
]);
// useState which creates the shopping cart list for me
const [shoppingList, setShoppingList] = useState([]);
// Function to add products to the cart or to increase the quantity of some
const addProduct = (id) => {
if (shoppingList.some((product) => product.id === id)) {
const increaseQuantity = shoppingList.map((product) => {
if (product.id === id) {
product.amount++;
return product;
} else {
return product;
}
});
setShoppingList(increaseQuantity);
} else {
const addNew = products.filter((product) => product.id === id);
setShoppingList([...shoppingList, ...addNew]);
}
};
// Function to remove products from the shopping list (shopping list cart)
const removeProduct = (id) => {
const remove = shoppingList.filter((product) => product.id !== id);
setShoppingList(remove);
};
return (
<div className="container">
<div className="row border border-2 border-danger">
<div className="col-6 border border-info">
<div className="row">
{products.map((product) => (
<AvailableProductsList
key={product.id}
product={product}
addProduct={addProduct}
/>
))}
</div>
</div>
<div className="col-6">
{shoppingList.map((product) => (
<ShoppingListCart
key={product.id}
product={product}
removeProduct={removeProduct}
/>
))}
</div>
</div>
</div>
);
};
答案 0 :(得分:0)
代替下面的代码
if (product.id === id) {
product.amount++;
return product;
} else {
return product;
}
改成
if (product.id === id) {
return { ...product, amount: product.amount + 1 };
}
return product;
产品是从产品数组中引用的。不要直接改变它。创建它的副本,然后进行更改