如何仅修改其道具而不影响其他项目来替换数组中的现有对象?

How to replace existing object in array only modifying its props and not affect to other items?

我正在尝试将商品添加到购物车。如果它在购物车中,我想相应地用更新的数量和总数替换这个项目,但我不想影响其他项目。如果它不在购物车中,我将其添加(if 语句的逻辑)。 else语句逻辑如何实现?

class ProductProvider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cart: [],
      modalOpen: false,
      modalProduct: {},
      cartTotal: 0,
    };
  }

  addToCart = (product) => {
    const index = this.state.cart.findIndex((item) => item.id === product.id);
    if (index === -1) {
      const tempProduct = { ...product };
      tempProduct.inCart = true;
      tempProduct.count = 1;
      const price = product.prices[0].amount;
      tempProduct.total = price;

      this.setState(
        () => {
          return { cart: [...this.state.cart, tempProduct] };
        },
        () => {
          this.addTotal();
        }
      );
    } else {
            // solution must be here
    }
  };

    addTotal = () => {
    let total = 0;
    this.state.cart.map((item) => (total += item.total));

    this.setState(() => {
      return {
        cartTotal: parseFloat(total.toFixed(2)),
      };
    });
  };
}

看起来像这种方法,我目前正在尝试在其他组件中应用效果很好。我需要测试它并适应以前的情况。

constructor(props) {
    super(props);
    this.state = {
      readMore: false,
      activeID: null,
      activeAtt: null,
      selectedAttributes: [],
    };
  }

  setAttributes = (name, value) => {
    const index = this.state.selectedAttributes.findIndex(
      (item) => item.name === name
    );
    if (index === -1) {
      const newAttribute = { name, value };

      this.setState(() => {
        return {
          selectedAttributes: [...this.state.selectedAttributes, newAttribute],
        };
      });
    } else {
      const tempAttributes = [...this.state.selectedAttributes];
      const selectedAttribute = tempAttributes.find(
        (attribute) => attribute.name === name
      );
      selectedAttribute.value = value;
      this.setState(() => {
        return { selectedAttributes: [...tempAttributes] };
      });
    }
else {
      const tempCart = [...this.state.cart];
      const selectedItem = tempCart.find((item) => item.id === product.id);
      selectedItem.selectedAttributes = attributes;
      selectedItem.count = selectedItem.count + 1;
      const price = product.prices[0].amount;
      selectedItem.total = selectedItem.total + price;

      this.setState(
        () => {
          return { cart: [...tempCart] };
        },
        () => {
          this.addTotal();
        }
      );
    }