本文先记录 @ObservedV2 装饰器 @Trace 装饰器 @Local 装饰器
当我们的数据结构有嵌套对象时,当只有嵌套对象属性发生变化,这时不能触发 View 刷新,看一下效果图和代码:
@Observed
class Child{
name:string='child'
}
@Observed
class Father{
name:string='father'
child:Child=new Child();
}
@Entry
@Component
struct test{
@State father:Father = new Father()
build() {
Stack(){
Column({space:30}){
Text(this.father.name).fontSize(30).fontColor(Color.Black)
Text(this.father.child.name).fontSize(30).fontColor(Color.Gray)
Row(){
Button('改变child属性').onClick(()=>{
//只有嵌套类对对象属性变化不能被监听到
this.father.child.name='child2'
})
Button('改变father属性').onClick(()=>{
this.father.name='father2'
})
}
}
}.alignContent(Alignment.Center)
.width('100%')
.height('100%')
}
}
复制代码
为了解决这种需求,需要引入 V2 所属装饰器,为了增强状态管理框架对类对象中属性的观测能力,开发者可以使用 @ObservedV2 装饰器和 @Trace 装饰器装饰类以及类中的属性。
概述
@ObservedV2 装饰器与 @Trace 装饰器用于装饰类以及类中的属性,使得被装饰的类和属性具有深度观测的能力:
@ObservedV2 装饰器与 @Trace 装饰器需要配合使用,单独使用 @ObservedV2 装饰器或 @Trace 装饰器没有任何作用。
被 @Trace 装饰器装饰的属性 property 变化时,仅会通知 property 关联的组件进行刷新。
在嵌套类中,嵌套类中的属性 property 被 @Trace 装饰且嵌套类被 @ObservedV2 装饰时,才具有触发 UI 刷新的能力。
在继承类中,父类或子类中的属性 property 被 @Trace 装饰且该 property 所在类被 @ObservedV2 装饰时,才具有触发 UI 刷新的能力。
未被 @Trace 装饰的属性用在 UI 中无法感知到变化,也无法触发 UI 刷新。
@ObservedV2 的类实例目前不支持使用 JSON.stringify 进行序列化。
@ObservedV2
class Child{
@Trace name:string='child'
}
@ObservedV2
class Father{
@Trace name:string='father'
child:Child=new Child();
}
@Entry
@ComponentV2
struct test2{
father:Father = new Father()
@Local message: string = "Hello";
build() {
Stack(){
Column({space:10}){
Text(this.message).fontSize(30)
Text(this.father.name).fontSize(30)
Text(this.father.child.name).fontSize(30)
Row(){
Button('locak修饰').onClick(()=>{
this.message='world'
})
Button('改变child属性').onClick(()=>{
this.father.child.name='child2'
})
Button('改变father属性').onClick(()=>{
this.father.name='father2'
})
}
}
}.alignContent(Alignment.Center)
.width('100%')
.height('100%')
}
}
复制代码
评论