ReactJS 处理购物车中的数量

ReactJS handling quantiteis in cart

在一个电子商务项目中,我制作了一个购物车,其功能可以在这里看到 codesandbox.io/s/confident-torvalds-smg72?file=/src/App.js

我的主要问题是,无论我在字段中输入多少数字,乘积只会增加 1

这是我的猜测

找不到具有良好可用性的好解决方案(我可以放置一个更新购物车按钮,但我无法处理 onChange,因为我不知道我有多少文件,我可以使用 +- 解决方案,但是最好在 fileld 中放入任意数字并自动更新购物车) 如果您有任何建议...

我认为您遇到问题的原因是,如果您调用 setCartcart 的值实际上不会更新,直到下一次呈现。因此,当您第二次调用 setCart([...cart]) 时,您正在扩展 cart

的原始版本

你可以通过使用函数更新器来解决这个问题,你传递一个接收最新版本 cart 作为第一个参数的函数:

setCart((latestCart) => ([...latestCart, ...newCart]);

我认为您应该考虑重组 cart 状态以更好地反映您如何使用数据,例如,如果您使用:

const [cart, setCart] = useState([
    { id: 1, name: "product 1", qty: 1 },
    { id: 2, name: "product 2", qti: 1 },
]);

// you can update the quantity using one call to setCart:
setCart(cart.map(item => {
    if (item.id === itemIWantToUpdate) {
         return { ...item, qty: newQuantity };
    }
    return item;
}));