HarmonyOS鸿蒙Next中关于状态管理V2中继承类场景的疑问
HarmonyOS鸿蒙Next中关于状态管理V2中继承类场景的疑问
在开发文档中提到:状态管理V2中继承类场景 @Trace
支持在类的继承场景中使用,无论是在基类还是继承类中,只有被 @Trace
装饰的属性才具有被观测变化的能力
并在文档的举例中,当我在 Son
中增加一个 id
属性也并不使用 @trace
,然后我在 Button
时使 id
改变,UI 中 id
也会刷新改变,但我并没有 @Trace
装饰呀,这不与上面描述的不符呀,是我理解有问题还是?
@ObservedV2
class GrandFather {
@Trace age: number = 0;
constructor(age: number) {
this.age = age;
}
}
class Father extends GrandFather{
constructor(father: number) {
super(father);
}
}
class Uncle extends GrandFather {
constructor(uncle: number) {
super(uncle);
}
}
class Son extends Father {
//增加一个属性id:
id:number = 0;
constructor(son: number) {
super(son);
}
}
class Cousin extends Uncle {
constructor(cousin: number) {
super(cousin);
}
}
@Entry
@ComponentV2
struct Index {
son: Son = new Son(0);
cousin: Cousin = new Cousin(0);
renderTimes: number = 0;
isRender(id: number): number {
console.info(`id: ${id} renderTimes: ${this.renderTimes}`);
this.renderTimes++;
return 40;
}
build() {
Row() {
Column() {
Text(`Son ${this.son.age},id:${this.son.id}`) //text中增加了id。 随着button点击改变了id的值,这个text中的id值也会随着刷新
.fontSize(this.isRender(1))
.fontWeight(FontWeight.Bold)
Text(`Cousin ${this.cousin.age}`)
.fontSize(this.isRender(2))
.fontWeight(FontWeight.Bold)
Button('change Son age')
.onClick(() => {
this.son.age++;
//添加id的自增即改变id的值
this.son.id++;
})
Button('change Cousin age')
.onClick(() => {
this.cousin.age++;
})
}
.width('100%')
}
.height('100%')
}
}
更多关于HarmonyOS鸿蒙Next中关于状态管理V2中继承类场景的疑问的实战教程也可以访问 https://www.itying.com/category-93-b0.html
刷新是因为age改变了,你把button中的age语句去掉试一下,
更多关于HarmonyOS鸿蒙Next中关于状态管理V2中继承类场景的疑问的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
是的,因为我将id 和age放在同一个text中,因为age改变刷新了text,所以id也一并刷新了,应该是这样的吧?当我把id拿出来放在另一个text中,就不会随着刷新改变了,
找HarmonyOS工作还需要会Flutter技术的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:BV1S4411E7LY/?p=17
如果只想要age刷新,可以用两个span,一个放age,一个放ID,
在HarmonyOS鸿蒙Next的状态管理V2中,继承类场景主要涉及状态共享与组件通信。通过继承State
类,子类可以访问父类的状态,并实现状态更新与同步。开发者需注意状态的生命周期管理,避免内存泄漏。建议使用@Observed
和@ObjectLink
注解来简化状态绑定与更新逻辑,确保UI与状态的一致性。