前言
在前两篇的组件内状态管理装饰器 @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;
}
与 V1 版本的 @Observed 和 @ObjectLink 的对比
从这几篇文章中也可以看到,V2 的装饰器都是解决了 V1版本装饰器存在的问题。在这里也没有例外。对于 V1 版本的 @Observed
来说,如果是嵌套类的属性变化,是无法直接监测的。我们需要使用自定义子组件加 @ObjectLink
的方案去解决。但如果嵌套层级多的话会导致代码结构复杂,不易维护。
所以,为了解决嵌套类属性无法直接监测的问题,鸿蒙官方推出了 V2 版本的@ObservedV2
和 @Trace
。
总结
@ObservedV2
和 @Trace
用于监测嵌套类属性的变化,两个装饰器均只能在类中使用,且需要配套使用。