无法在React中克隆对象数组

问题描述 投票:0回答:1

我试图让我的汉堡工作,不幸的是我发现了一个问题,我不知道如何解决或为什么不工作...请HEEEELP!

项目中的想法是从一组预先定义的成分,价格和初始数量开始...在我看来,所有汉堡都必须有生菜和肉...所以我创建了一个名为ORIGINALBURGER的对象,创建时该类,使用构造函数通过克隆原始对象将ORIGINALBURGER分配给该状态

问题:我无法使用spread或任何其他方法克隆我的原始汉堡对象。每次我更新状态“ingredientes”,它也会修改我的原始对象......

我错过了什么吗?请检查下面的代码并感谢他们帮助这个新手:

        import React, { Component } from "react";
import Aux from "../../hoc/Aux";
import Burguer from "../../components/Burguer/Burguer";
import BuildControls from "../../components/Burguer/BuildControls/BuildControls";

const OriginalIngredients = [
  { PublicName: "Salad", Type: "salad", Quantity: 1, Price: 0.65 },
  { PublicName: "Bacon", Type: "bacon", Quantity: 0, Price: 1.65 },
  {
    PublicName: "American Cheese",
    Type: "cheese",
    Quantity: 0,
    Price: 0.99
  },
  { PublicName: "Meat Patty", Type: "meat", Quantity: 1, Price: 2.65 }
];

class BurguerBuilder extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // ---> OPTION B ---> ingredientes: ORIGINALBURGUER.map(a => ({ ...a })),
      ingredientes: [...OriginalIngredients],
      TotalPrice: 0
    };
  }

  render() {
    const { ingredientes } = this.state;

    return (
      <Aux>
        <Burguer ingredients={ingredientes} />
        <BuildControls
          ingredients={ingredientes}
          AddIngredientEvent={this.handleAddIngredient}
          RemoveIngredientEvent={this.handleRemoveIngredient}
          changeAmtEvent={this.handleIngredientChangeAmt}
          ResetIngredientsEvent={this.hanldeResetIngredients}
        />
      </Aux>
    );
  }

  componentDidMount() {
    const TotalBurguerPrice = this.CalculateBurguerPrice();
    this.setState({ TotalPrice: TotalBurguerPrice });
  }

  CalculateBurguerPrice() {
    return 50;
  }

  hanldeResetIngredients = () => {
    const IngredientesOriginales = [...OriginalIngredients];
    this.setState({ ingredientes: IngredientesOriginales });
  };

  handleRemoveIngredient = type => {
    const ingredientes = [...this.state.ingredientes];
    if (ingredientes.find(f => f.Type === type).Quantity > 0)
      ingredientes.find(f => f.Type === type).Quantity--;
    this.setState({ ingredientes });
  };

  handleAddIngredient = type => {
    const ingredientes = [...this.state.ingredientes];
    ingredientes.find(f => f.Type === type).Quantity++;
    this.setState({ ingredientes });
    console.log("state content", this.state.ingredientes);
    console.log("original burger", OriginalIngredients);
  };

  handleIngredientChangeAmt = (evento, tipo) => {
    const ingredientes = [...this.state.ingredientes];
    const ingrediente = ingredientes.find(i => i.Type === tipo);

    if (evento.target.value === "") ingrediente.Quantity = 0;
    else if (evento.target.value >= 0)
      ingrediente.Quantity = evento.target.value;
    else ingrediente.Quantity = 0;

    this.setState({ ingredientes });
  };
}

export default BurguerBuilder;

例如,在名为hanldeResetIngredients的方法中,我想将我的对象的原始版本分配给当前状态,但是当我看到时,状态和原始对象都已更改。谢谢你的帮助。

reactjs
1个回答
0
投票

Spread正在创建一个浅表副本,这意味着它遍历您的数组并复制对该数组中对象的引用,而不是实际复制每个对象。你需要遍历你的数组并传播每个对象,即:

OriginalIngredients.map( (ingredient) => {
    return {...ingredient}
});
© www.soinside.com 2019 - 2024. All rights reserved.