✨本人自己开发的开源项目:土拨鼠充电系统
✨踩坑不易,还希望各位大佬支持一下,在GitHub给我点个 Start ⭐⭐👍👍
✍GitHub开源项目地址👉:https://github.com/cheinlu/groundhog-charging-system
一、介绍
@Watch应用于对状态变量的监听。如果需要关注某个状态变量的值是否改变,可以使用@Watch为状态变量设置回调函数。
1.1、变量与类型说明
1.2、具体行为与限制条件
一、具体行为表现
①当观察到状态变量的变化时候,@Watch的回调方法将被触发;
②@Watch方法在自定义组件的属性变更之后同步执行;
③如果在@Watch的方法里改变了其他的状态变量,也会引起状态变更和@Watch的执行;
④在第一次初始化的时候,@Watch装饰的方法不会被调用,只有在后续状态改变时,才会调用@Watch回调方法。
二、限制条件
①建议避免无限循环,不要在@Watch的回调方法里修改当前装饰的状态变量
②应关注性能,属性值更新函数会延迟组件的重新渲染,所以回调函数应仅执行快速运算;
③不建议在@Watch函数中调用async await,异步行为可能会导致重新渲染速度的性能问题。
三、使用场景
3.1、语法
@State @Watch('onChange') count:number = 0
//监听方法
onChange():void{}
3.2、@Watch和自定义组件更新
@Entry
@Component
struct CountModifier {
@State count: number = 0;
build() {
Column({space:15}) {
Button('count自增')
.onClick(() => {
this.count++
})
TotalView({ count: this.count })
}.width('100%').margin({top:100})
}
}
//子组件 TotalView
@Component
struct TotalView {
@Prop @Watch('onCountUpdated') count: number;
@State total: number = 0;
// @Watch 回调
onCountUpdated(propName: string): void {
this.total += this.count;
}
build() {
Text(`Total: ${this.total}`)
}
}
步骤说明:
父组件CountModifier,子组件TotalView
1、父组件点击按钮count自增
2、由于@State count变量更改,子组件中的@Prop被更新,其@Watch('onCountUpdated')方法被调用,更新了子组件中的total变量。
3、子组件中的Text重新渲染
3.3、@Watch与@Link组合使用
class PurchaseItem {
static NextId: number = 0;
public id: number;
public price: number;
constructor(price: number) {
this.id = PurchaseItem.NextId++;
this.price = price;
}
}
@Entry
@Component
struct BasketModifier {
@State shopBasket: PurchaseItem[] = [];
build() {
Column({space:10}) {
Button('Add to basket')
.onClick(() => {
this.shopBasket.push(new PurchaseItem(Math.round(100 * Math.random())))
})
BasketViewer({ shopBasket: $shopBasket })
}.width('100%').margin({top:100})
}
}
//子组件 BasketViewer
@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({space:10}) {
ForEach(this.shopBasket,
(item) => {
Text(`Price: ${item.price.toFixed(2)} €`)
},
item => item.id.toString()
)
Text(`Total: ${this.totalPurchase.toFixed(2)} €`)
}
}
}
步骤说明:
父组件BasketModifier,子组件BasketViewer
1、父组件点击按钮时向子组件 shopBasket中添加条目
2、@Link装饰的子组件 shopBasket值发生变化;
3、在子组件调用@Watch函数onBasketUpdated 用来更新子组件中totalPurchase的值
4、@Link shopBasket的改变,新增了数组项,ForEach组件会执行item Builder,渲染构建新的Item项;@State totalPurchase改变,对应的Text组件也重新渲染;重新渲染是异步发生的。
🚀🚀🚀 踩坑不易,还希望各位大佬支持一下
📃 我的土拨鼠开源项目:
✍Gitee开源项目地址👉:https://gitee.com/cheinlu/groundhog-charging-system
✍GitHub开源项目地址👉:https://github.com/cheinlu/groundhog-charging-system
📃 我的鸿蒙NEXT轮播图开源组件:鸿蒙NEXT-轮播图控件: 使用HarmonyOS NEXT开发的轮播图组件,包含自定义角标
最后:👏👏😊😊😊👍👍