学习笔记(四十五):状态管理@Watch装饰器

概述

@Watch应用于对状态变量的监听。如果开发者需要关注某个状态变量的值是否改变,可以使用@Watch为状态变量设置回调函数。

观察变化和行为表现

  1. 当观察到状态变量的变化(包括双向绑定的AppStorage和LocalStorage中对应的key发生的变化)的时候,对应的@Watch的回调方法将被触发;

  2. @Watch方法在自定义组件的属性变更之后同步执行;

  3. 如果在@Watch的方法里改变了其他的状态变量,也会引起状态变更和@Watch的执行;

  4. 在第一次初始化的时候,@Watch装饰的方法不会被调用,即认为初始化不是状态变量的改变。只有在后续状态改变时,才会调用@Watch回调方法。

限制条件

  • 建议开发者避免无限循环。循环可能是因为在@Watch的回调方法里直接或者间接地修改了同一个状态变量引起的。

  • 为了避免循环的产生,建议不要在@Watch的回调方法里修改当前装饰的状态变量;

  • 开发者应关注性能,属性值更新函数会延迟组件的重新渲染(具体请见上面的行为表现),因此,回调函数应仅执行快速运算;

  • 不建议在@Watch函数中调用async await,因为@Watch设计的用途是为了快速的计算,异步行为可能会导致重新渲染速度的性能问题。

使用示例
/**
 * @author : xqx
 * @create_day : 2024/11/21
 * @description : 首页
 */
import { HMRouter } from "@hadss/hmrouter";
import { ViewEntity } from "../animation/ViewEntity";
import { CommonView } from "../components/CommonView";

@HMRouter({
  pageUrl: 'Main',
  singleton: true,
  lifecycle: 'ExitAppLifecycle',
  animator: 'pageAnimator'
})
@Component
export struct Main {
  @State count: number = 0;

  build() {
    Column() {
      Button('add to basket')
        .onClick(() => {
          this.count++
        })
      TotalView({ count: this.count })
    }
  }
}


@Component
struct TotalView {
  @Prop @Watch('onCountUpdated') count: number = 0;
  @State total: number = 0;
  // @Watch 回调
  onCountUpdated(propName: string): void {
    this.total += this.count;
  }

  build() {
    Text(`Total: ${this.total}`)
  }
}

 

 
posted @ 2024-11-24 23:26  听着music睡  阅读(10)  评论(0编辑  收藏  举报