状态管理@ObjectLink @Observed
ObjectLink 和 Observed类装饰器用于在涉及嵌套对象或数组的场景中进行双向数据同步
被Observed装饰的类,可以被观察到属性的变化
子组件中ObjectLink装饰器装饰的状态变量用于接收Observed装饰的类的实例,和父组件中对应的状态变量建立双向数据绑定。这个实例可以是数组中的被Observed装饰的项,或者是class object中的属性,这个属性同样也需要被Observed装饰
单独使用Observed是没有任何作用的,需要搭配ObjectLink或者Prop使用
@Observed
class Person {
name: string;
age: number;
gf?: Person
constructor(name: string, age: number, gf?: Person) {
this.name = name;
this.age = age;
this.gf = gf;
}
}
@Component
struct Child {
@ObjectLink p:Person
build() {
Column(){
Text(`${this.p.name}:${this.p.age}`)
.onClick(()=>{
this.p.age++
})
.fontSize(25)
}
}
}
@Entry
@Component
struct Parent {
@State p: Person = new Person('Jack', 32, new Person('Rose', 12))
build() {
Column() {
Child({p:this.p.gf})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
// 如果上面不加@Observed和@ObjectLink 那么gf.age 不会受到监听,点击++页面视图不改变
@Watch 监听状态变量,去执行回调函数
@Entry
@Component
struct Index {
@State
@Watch('myCallback')
count: number = 0;
// 当count变化时会执行此函数
myCallback(){
console.log('count发生了改变'+this.count);
}
build() {
Row() {
Column() {
Text(`@Watch回调函数被第${this.count}次调用`)
.fontWeight(FontWeight.Bold)
.fontSize(25)
Button('点击count+1')
.onClick(()=>{
this.count++
})
}
.width('100%')
}
.height('100%')
}
}