在HarmonyOS NEXT开发中关于数组中class更改,List不触发更新问题?

在HarmonyOS NEXT开发中关于数组中class更改,List不触发更新问题?

阅读 572
1 个回答

你可以参考以下demo,@Watch与@Link组合使用 ,相关文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides...

class PurchaseItem { 
  static NextId: number = 0; 
  public id: number; 
  public price: number; 
 
  constructor(price: number) { 
    this.id = PurchaseItem.NextId++; 
    this.price = price; 
  } 
} 
 
@Component 
struct BasketViewer { 
  @Link @Watch('onBasketUpdated') shopBasket: PurchaseItem[]; 
  @State totalPurchase: number = 0; 
 
  updateTotal(): number { 
    let total = this.shopBasket.reduce((sum, i) => sum + i.price, 0); 
    // 超过100欧元可享受折扣 
    if (total >= 100) { 
      total = 0.9 * total; 
    } 
    return total; 
  } 
  // @Watch 回调 
  onBasketUpdated(propName: string): void { 
    this.totalPurchase = this.updateTotal(); 
  } 
 
  build() { 
    Column() { 
      ForEach(this.shopBasket, 
        (item: PurchaseItem) => { 
          Text(`Price: ${item.price.toFixed(2)} €`) 
        }, 
        (item: PurchaseItem) => item.id.toString() 
      ) 
      Text(`Total: ${this.totalPurchase.toFixed(2)} €`) 
    } 
  } 
} 
 
@Entry 
@Component 
struct BasketModifier { 
  @State shopBasket: PurchaseItem[] = []; 
 
  build() { 
    Column() { 
      Button('Add to basket') 
        .onClick(() => { 
          this.shopBasket.push(new PurchaseItem(Math.round(100 * Math.random()))) 
        }) 
      BasketViewer({ shopBasket: $shopBasket }) 
    } 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进