首页 > 解决方案 > 如何保护数组不被刷新

问题描述

我有基于 Clothes 和 Orders 模型的衣服和订单表和数组。每当我将衣服元素推入 Orders 数组时,尤其是更新选择的衣服数量和价格时,衣服数组也会更新,我不想要它。我想让我的数组保持不变。我在互联网上搜索它但没有用。这是我在下面尝试的。另外为了清楚起见,我会在这里添加图片

https://imge.to/i/vg2aYm

https://imge.to/i/vg2uvF

HTML

    <table class="table table-sm">
        <thead>
          <tr>
            <th scope="col">Clothes</th>
            <th scope="col">Price</th>
            <th scope="col"></th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let i of clothesList;let a = index">
            <td>{{i.name}}</td>
            <td>{{i.price}}$</td>
            <td><button class="btn btn-alert" (click)="onAddItem(i)" >Add To Cart</button></td>
          </tr>
        </tbody>
      </table>

   <table class="table" *ngIf="orders.length>0">
                    <thead>
                      <tr>
                        <th scope="col">Clothes</th>
                        <th scope="col">Amount</th>
                        <th scope="col">Price</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr *ngFor="let order of orders;">
                        <td>{{order.name}}</td>
                        <td>{{order.amount}}</td>
                        <td>{{order.price}}</td>
                      </tr>
                    </tbody>
                    <hr>
                    <strong>Total Cost: {{totalCost}}</strong>
                  </table>

TS

export class AppComponent  {
 private clothesList:Clothes[]=[
   new Clothes(1,'Hat',500,1),
   new Clothes(2,'Shoes',150,1),
   new Clothes(3,'Pants',100,1),
   new Clothes(4,'Jacket',200,1),
   new Clothes(5,'T-Shirt',120,1),
   new Clothes(6,'Souvether',150,1),
   new Clothes(7,'Scarf',400,1)
 ];
    private orders:Order[]=[];

    onAddItem(value)
  {   
   if(this.orders.find(i => i.name===value.name))
   {
      let myIndex= this.orders.indexOf(value);
      value.amount++;
      this.orders[myIndex].price+=this.orders[myIndex].price;
   } 
  else
   {
    this.orders.push(value);
   }
  }
}

标签: javascripthtmlarraysangulartypescript

解决方案


这是因为衣服和订单数组中的元素共享相同的引用,您需要深度克隆您的对象以破坏引用:尝试以下操作:

onAddItem(value){
        let order = this.orders.find(i => i.name === value.name);
        if (order) {
            value.amount++;
            order.price *= 2;
        }
        else {
            this.orders.push(JSON.parse(JSON.stringify(value))); // break the reference
        }
    }

推荐阅读