HarmonyOS - 嵌套类属性状态管理装饰器:ObservedV2 和 Trace

前言

在前两篇的组件内状态管理装饰器 @Local 和 组件外部输入状态管理装饰器 @Param 的介绍中,我们提到:对于上面的两个装饰器装饰的类对象,只能监测到类对象赋值的变化,并不能检测到属性或嵌套类属性的变化。但在常见的开发场景中,嵌套类是很普遍的情况,那这种情况我们应该如何进行状态管理呢?

答案就是今天要讲的 @ObservedV2@Trace

@ObservedV2 和 @Trace

这两个装饰器的作用就是当嵌套类的属性发生变化时,绑定的 UI 组件会自动更新。首先,我们来看下如何在代码中使用这两个装饰器。

假设我们有这样一个需求,展示每个玩家的宠物猫的数量,并且页面有一个按钮可以增加玩家的宠物猫数量。 代码示例如下:

typescript 复制代码
class Player {
  name: string;
  age: number;
  cat: Cat;

  constructor(name: string, age: number, cat: Cat) {
    this.name = name;
    this.age = age;
    this.cat = cat;
  }
}

@ObservedV2 class Cat  {
  @Trace count: number;

  constructor( count: number) {
    this.count = count;
  }
}


@Entry
@ComponentV2
struct Index {
  private player = new Player("Tom", 10, new Cat(0))

  build() {
    Column() {
      Text("Count:" + this.player.cat.count)
      Button("Add").onClick(() => {
        this.player.cat.count += 1
      })
    }
    .height('100%')
    .width('100%')
  }
}

上述代码中,我们定义了一个 Player 的类代表玩家,一个 Cat 的类代表宠物。因为需要监测宠物猫的数量,所以嵌套类 Cat 我们需要用 @ObservedV2 来装饰,而它需要监测变化的 count 我们则需要 @Trace 来进行装饰。

需要注意的是,组件的装饰器我们最好改成 @ComponentV2,原因有以下两个:

  • 虽然 @Component 也能正常使用,但这两个装饰器毕竟是 V2 版本的,最好还是用 V2 配套的组件装饰器。
  • @ObservedV2@Trace 是不能与 V1 版本的状态装饰器 @State 等混用的,会编译报错。统一用 @ComponentV2 也可以避免该问题。

了解完 @ObservedV2@Trace 的使用方式,下面来看一下它俩的注意事项!

注意事项

首先需要注意的是,@ObservedV2 只能应用于类,不能用于结构体,比如下面的代码会编译报错:

scss 复制代码
//编译报错:The '@ObservedV2' decorator can only be used in 'class'. <ArkTSCheck>
@ObservedV2 struct Cat  {
  @Trace count: number;

  constructor( count: number) {
    this.count = count;
  }
}

而对于 @Trace 来说,需要和 @ObservedV2 配套使用,对没有使用 @ObservedV2 修饰的类属性使用 @Trace 也会编译报错,比如下面的代码:

typescript 复制代码
// 编译报错:The '@Trace' decorator can only be used within a 'class' decorated with 'ObservedV2'. <ArkTSCheck>
class Cat  {
  @Trace count: number;

  constructor( count: number) {
    this.count = count;
  }
}

当然,@Trace 也是只能用在类中,不能用在组件中:

less 复制代码
@ComponentV2
struct Index {
// 编译报错:The '@Trace' decorator can only be used in 'class'. <ArkTSCheck>
 @Trace num: number = 0;
}

从这几篇文章中也可以看到,V2 的装饰器都是解决了 V1版本装饰器存在的问题。在这里也没有例外。对于 V1 版本的 @Observed 来说,如果是嵌套类的属性变化,是无法直接监测的。我们需要使用自定义子组件加 @ObjectLink 的方案去解决。但如果嵌套层级多的话会导致代码结构复杂,不易维护。

所以,为了解决嵌套类属性无法直接监测的问题,鸿蒙官方推出了 V2 版本的@ObservedV2@Trace

总结

@ObservedV2@Trace 用于监测嵌套类属性的变化,两个装饰器均只能在类中使用,且需要配套使用。

相关推荐
ONEDAY1 天前
HarmonyOS 多 Product 构建实践:一套代码生成多个产物
harmonyos
TT_Close1 天前
别劝退了!5秒搞定 Flutter 鸿蒙 FVM 起跑线
flutter·harmonyos·visual studio code
TrisighT1 天前
ArkTS 列表滚动时为什么会闪现旧数据?我扒了 LazyForEach 的复用逻辑
harmonyos·arkts·arkui
MonkeyKing1 天前
鸿蒙ArkTS深度剖析:ArkTS与TS/JS核心差异、静态强类型实战优势
typescript·harmonyos
TrisighT1 天前
Electron鸿蒙PC上写日志文件,我被权限和路径坑了两次
electron·harmonyos
TrisighT2 天前
一个下午搞定 ArkTS 折叠面板?结果我从两点写到晚上九点
harmonyos·arkts·arkui
花椒技术5 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
一维Ace5 天前
HarmonyOS ArkTS 按钮组件全解:Button、Toggle 状态交互实战
harmonyos
anyup6 天前
来简单聊聊鸿蒙开发,万元奖金的事~
前端·华为·harmonyos
Georgewu6 天前
【无测试机别害怕】华为云鸿蒙云手机南:从零到联调全流程详解
harmonyos