reactjs - 为什么当我更新一个 useState 时它会更新另一个而不调用它(反应钩子)?
问题描述
我在 react 和编程本身中迈出了第一步,为此我制作了一个简单的购物车,它允许我将要购买的产品添加到以空数组开头的 useState 中。我也有其他使用状态的产品。当我通过具有 addProduct 功能的按钮添加产品时,它会验证产品是否已经在列表中,如果是,则如果没有添加,它会增加数量。问题是,当产品已经存在时,它会很好地增加数量,但它也会在处于另一个使用状态的产品中做到这一点。从此我扩展了 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>
);
};
解决方案
而不是下面的代码
if (product.id === id) {
product.amount++;
return product;
} else {
return product;
}
将其更改为
if (product.id === id) {
return { ...product, amount: product.amount + 1 };
}
return product;
产品是从产品数组中引用的。不要直接改变它。创建它的副本,然后进行更改
推荐阅读
- kernel - 在 RaspberryPi 3 上使用 xvisor 在 U-boot 命令提示符下卡在“正在启动内核.....”
- python - Python thread_local 数据
- javascript - Tone JS - 过滤器不适用于采样器
- c# - 如何使用不在基类中的属性
- java - JUnit 嵌套测试未运行
- csh - 如何在c-shell中将特殊字符作为参数传递
- python - python setup.py egg_info 检查日志以获得完整的命令输出 为什么要安装 instagram-scraper
- string - 如何将持续时间字符串格式化为天-小时-分钟字符串?
- postgresql - 在 Postgres 中是否有函数的内部版本号之类的东西?
- r - 无法在 CentOS7 上安装 facebook 先知的 R 库