【问题标题】:Trigger manually ngFor or making it update DOM correctly手动触发 ngFor 或使其正确更新 DOM
【发布时间】:2020-04-27 16:58:10
【问题描述】:

我有这个代码

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 没有触发它不会添加具有该类别的食物

我该如何解决这个问题?

【问题讨论】:

    标签: angular ionic-framework ionic4 ngfor


    【解决方案1】:

    您的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 =&gt; ({...foodAllergy})),取决于您在foodAllergy 中有多少深度嵌套的对象/数组,您必须不可变地复制它们。

    所以说如果foodAllergy看起来像{ name: 'Peanuts', x: [1, 2, 3], y: { a: 1, b: 2 } },它会变成:

    ...this.foodAllergies.map(foodAllergy => ({
                                                ...foodAllergy, 
                                                x: [...foodAllergy.x], 
                                                y: {... foodAllergy.y } 
                               }))
    

    【讨论】:

    • 非常感谢,感谢您的回答,我已经解决了。没有必要使用 array.map 但有效的解决方案是: this.foodAllergies = [...this.foodAllergies, res.data] 不知道为什么 this.foodAllergies.push(res.data) 没有'不起作用(可能是因为创建一个新数组会使 ngFor 触发而不是更新现有数组),但是以这种方式它可以工作!
    猜你喜欢
    • 1970-01-01
    • 2017-10-03
    • 2015-07-31
    • 2015-07-14
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多