HarmonyOS @Observed/@ObjectLink装饰器可以观察三层四层的嵌套么,第三层数据修改但视图不更新

testA1不更新,testA2正常,代码如下:

@Observed
export class B {
  testB = 0
  testA: A = new A()
}
@Observed
export class A {
  a = 0
}
@Entry
@Component
struct ObservedQ1 {
  @State itemB: B = new B()
  build() {
    Column() {
      Column() {
        TestB({
          itemB: this.itemB,
          itemA: this.itemB.testA
        })
          .margin({ bottom: 20 })
        Button("this.itemB.testA.a++")
          .onClick(() => {
            this.itemB.testA.a += 1
          })
      }.width('100%')
      .backgroundColor('#33ff0000')
    }
  }
}
@Component
struct TestB {
  @ObjectLink itemB: B
  @ObjectLink itemA: A
  build() {
    Column() {
      Text(`testA1 : ${this.itemB.testA.a}`)
      Text(`testA2 : ${this.itemA.a}`)
    }
  }
}
HarmonyOS
2024-12-23 14:50:30
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zxjiu

可以使用@Trace配合@ObservedV2,参考链接:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-new-observedv2-and-trace-V5#嵌套类场景

参考示例:

@ObservedV2
export class B {
  testB = 0
  testA: A = new A()
}

@ObservedV2
export class A {
  @Trace a = 0
}

@Entry
@ComponentV2
struct ObservedQ1 {
  itemB: B = new B()

  build() {
    Column() {
      Column() {
        Text(`testA1 : ${this.itemB.testA.a}`)
        Button("this.itemB.testA.a++")
          .onClick(() => {
            this.itemB.testA.a += 1
          })
      }.width('100%')
      .backgroundColor('#33ff0000')
    }
  }
}
分享
微博
QQ
微信
回复
2024-12-23 17:53:47
相关问题
HarmonyOS 三层架构HSP跳转问题
850浏览 • 1回复 待解决
arkui三层结构分别是什么?
723浏览 • 1回复 待解决
HarmonyOS ArkWeb同渲染嵌套能力
1056浏览 • 1回复 待解决
ArkTS通过接口访问C++对象
996浏览 • 1回复 待解决