首页 > 解决方案 > 更新数组挂钩中的对象反应js

问题描述

我试图通过按“向上”按钮来更新数量。

这是我的代码。

const increaseHandler = (x) => {

    let newCart = [...props.cartItems];

    let exist = newCart.find((item) => item.id === x.id);
    if (exist) {
        exist.quantity++;
    } else {
        exist = {
            ...props.cartItems,
            quantity: 1,
        };
    }
    newCart.push(exist);
    props.setCartItems(newCart);
};

这是按钮:

<button className="up" onClick={() => increaseHandler(items)}>
    up
</button>

每次我单击“向上”按钮时,它都会在 cartItems 上附加该项目的副本

初始 cartItems 的图像

此处增加数量后的问题图片

我增加了数量,但它将对象附加到数组中。

标签: javascriptreactjsshopping-cart

解决方案


即使您对购物车项目数组进行了浅层复制,您仍然会使用后期增量来改变各个项目。

const increaseHandler = (x) => {
    let newCart = [...props.cartItems];

    let exist = newCart.find((item) => item.id === x.id);
    if (exist) {
        exist.quantity++; // <-- mutation!!
    } else {
        exist = {
            ...props.cartItems,
            quantity: 1,
        };
    }
    newCart.push(exist); // <-- adds duplicate items
    props.setCartItems(newCart);
};

您仍然需要创建一个新的项目引用,浅复制属性并更新quantity属性。您应该只将元素推送到购物车数组中。

const increaseHandler = (x) => {
    const newCart = [...props.cartItems];

    let exist = newCart.find((item) => item.id === x.id);
    if (exist) {
        exist = {
            ...exist,
            quantity: exist.quantity + 1;
        };
    } else {
        exist = {
            ...props.cartItems,
            quantity: 1,
        };
        newCart.push(exist);
    }
    
    props.setCartItems(newCart);
};

将前一个状态映射到下一个状态更为常见,我建议使用功能状态更新来确保从前一个状态正确更新,而不是在回调范围内关闭任何状态(可能是陈旧的)。

const increaseHandler = (x) => {
  props.setCartItems(items => {
    const inCart = items.some((item) => item.id === x.id);
    if (inCart) {
      return items.map((item) => item.id === x.id 
        ? {
          ...item,
          quantity: item.quantity + 1,
        } 
        : item);
    }
    return items.concat({
      ...props.cartItems,
      quantity: 1,
    });
  });
};

推荐阅读