手动触发 ngFor 或使其正确更新 DOM
Trigger manually ngFor or making it update DOM correctly
我有这个代码
TS
modal.onDidDismiss().then(res => {
if (res.data !== undefined) {
this.foodAllergies.push(res.data)
if (this.categories.length === 0) {
this.categories.push(res.data.category)
} else {
if (!this.categories.includes(res.data.category)) {
this.categories.push(res.data.category)
}
}
}
});
HTML
<ion-grid>
<ion-row *ngFor="let category of categories">
<ion-col>
<h3>{{category}}</h3>
<ion-list>
<ion-item *ngFor="let food of foodAllergies | categoryFilter: category">
<ion-label>{{food.name}}</ion-label>
</ion-item>
</ion-list>
</ion-col>
</ion-row>
</ion-grid>
因此,每当我向类别数组添加新类别时,视图都会正确更新,显示该类别中的食物
问题是,当我添加类别数组中已经存在的类别时,视图无法正确更新,因为第二个 ngFor 不会触发它不会添加该类别的食物
我该如何解决这个问题?
你的if() { ... } else { if() { ... } }
也在做同样的事情,我觉得很奇怪。
尝试以 immutable
方式更新 foodAllergies
(更改其引用),看看这是否有助于并启动更改检测。
modal.onDidDismiss().then(res => {
if (res.data !== undefined) {
this.foodAllergies = [...this.foodAllergies.map(foodAllergy => ({...foodAllergy})), res.data];
this.foodAllergies.push(res.data);
// you can keep your if and else if but I have removed them here for this example
this.categories.push(res.data.category);
}
}
});
对于 ...this.foodAllergies.map(foodAllergy => ({...foodAllergy}))
,根据 foodAllergy
中嵌套的深度 objects/arrays,您必须不可变地复制它们。
所以说如果 foodAllergy
看起来像 { name: 'Peanuts', x: [1, 2, 3], y: { a: 1, b: 2 } }
,它将变成:
...this.foodAllergies.map(foodAllergy => ({
...foodAllergy,
x: [...foodAllergy.x],
y: {... foodAllergy.y }
}))
我有这个代码
TS
modal.onDidDismiss().then(res => {
if (res.data !== undefined) {
this.foodAllergies.push(res.data)
if (this.categories.length === 0) {
this.categories.push(res.data.category)
} else {
if (!this.categories.includes(res.data.category)) {
this.categories.push(res.data.category)
}
}
}
});
HTML
<ion-grid>
<ion-row *ngFor="let category of categories">
<ion-col>
<h3>{{category}}</h3>
<ion-list>
<ion-item *ngFor="let food of foodAllergies | categoryFilter: category">
<ion-label>{{food.name}}</ion-label>
</ion-item>
</ion-list>
</ion-col>
</ion-row>
</ion-grid>
因此,每当我向类别数组添加新类别时,视图都会正确更新,显示该类别中的食物 问题是,当我添加类别数组中已经存在的类别时,视图无法正确更新,因为第二个 ngFor 不会触发它不会添加该类别的食物
我该如何解决这个问题?
你的if() { ... } else { if() { ... } }
也在做同样的事情,我觉得很奇怪。
尝试以 immutable
方式更新 foodAllergies
(更改其引用),看看这是否有助于并启动更改检测。
modal.onDidDismiss().then(res => {
if (res.data !== undefined) {
this.foodAllergies = [...this.foodAllergies.map(foodAllergy => ({...foodAllergy})), res.data];
this.foodAllergies.push(res.data);
// you can keep your if and else if but I have removed them here for this example
this.categories.push(res.data.category);
}
}
});
对于 ...this.foodAllergies.map(foodAllergy => ({...foodAllergy}))
,根据 foodAllergy
中嵌套的深度 objects/arrays,您必须不可变地复制它们。
所以说如果 foodAllergy
看起来像 { name: 'Peanuts', x: [1, 2, 3], y: { a: 1, b: 2 } }
,它将变成:
...this.foodAllergies.map(foodAllergy => ({
...foodAllergy,
x: [...foodAllergy.x],
y: {... foodAllergy.y }
}))