首页 > 解决方案 > ionic 3 输入数据绑定正在更新相同类型的不同数组

问题描述

我的 ionic 3 应用程序之一的输入数据绑定存在问题。每当输入更改时,就会更改相同类型的不同数组的数组值。

这是我的 HTML

<ion-list>
    <ion-item-sliding *ngFor="let item of storageItem ; index as i">
        <div class ="itemList">

            <input type="number" [value] ="item.storageOrderQuantity"  (blur)="updateInputItemValue(item)"
                             [(ngModel)]="item.storageOrderQuantity" />

        </div>
    </ion-item-sliding>
</ion-list>

当输入值发生变化时,它会更新“storageItem”数组以及具有相同对象的其他数组(还有一些其他数组“item”)。

这是我的数组声明。项目是一个模型类。

item: Item[];
storageItem: Item[] = [];

storageItem' 是 'item 的子集

谁能告诉数据投标中的错误是什么?

标签: ionic-frameworkionic3

解决方案


您提到storageItem 是 item 的子集

你可能已经知道了,数组和对象使用了assign-by-reference 的概念。如果您不知道这一点,请阅读下面关于 Medium 的文章。

https://medium.com/@naveenkarippai/learning-how-references-work-in-javascript-a066a4e15600

因此,如果您在两个数组中都有相同的对象,那么更新一个数组将更新另一个数组,

const obj = { name : 'value' };
const arr1 = [1,2,3,obj];
const arr2 = [4,5,6,obj];

obj.name = 'yash'; // both arrays will have updated object

现在,如果您想避免这种情况,那么您可以在将其用于另一个数组之前创建对象的副本。

参考https://flaviocopes.com/how-to-clone-javascript-object/

item: Item[] = [
    { id : 'item1', list : [] }, 
    { id : 'item2', list : [] }, 
    { id : 'storageItem', list : [...storageItem] }
];
storageItem: Item[] = [list of storage items];

现在storageItemitem > id='storageItem'指向不同的数组。所以你的模板只会更新storageItem现在。


推荐阅读