HarmonyOS @State修饰@observed装饰的对象, 对象里的数组改变, 不会触发ui刷新

@Preview
@Component
export struct OvenDemePage {
  @State vm: VM = new VM([])

  aboutToAppear(): void {
    this.vm.push()
  }

  build() {
    NavDestination() {

      Column() {
        Text('click')
          .fontSize(50)
          .onClick(() => {
            this.vm.datas[0].title = 'ovnekjskdaljfa'
            this.vm.push()
          })
      }.height(Percent.P20)
      .justifyContent(FlexAlign.Center)

      List({ space: 10 }) {
        ForEach(this.vm.datas, (item: Item, index: number) => {
          ListItem() {
            JJJ({ data: item })
          }
        }, (item: Item, index: number) => index + "")
      }.layoutWeight(1)

    }.hideTitleBar(true)
    .onBackPressed(() => {
      DeepalRouter.pop()
      return true
    })
  }
}

@Preview
@Component
export struct JJJ {
  @ObjectLink data: Item
  build() {
    Text(this.data.title).fontSize(30)
  }
}

/**
 *
 */
@Observed
export class VM {
  datas: Item[] = []

  constructor(datas: Item[]) {
    this.datas = datas
  }


  push() {
    for (let i = 0; i < 10; i++) {
      this.datas.push(new Item(Math.random() + " title"))
    }
  }
}

/**
 * item
 */
@Observed
export class Item {
  title?: string
  constructor(title: string) {
    this.title = title
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
HarmonyOS
2024-12-24 17:02:30
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

因为@Observed装饰器可以观察到嵌套对象的属性变化,其他装饰器仅能观察到第二层的变化。需要将具有观测能力的类对象绑定组件,来确保当改变这些类对象的内容时,UI能够正常的刷新(New一个继承了Array的对象而不是自定义数组)。具体参考如下链接,里面列举了几种失效场景,并提供了正确的写法。

相关文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-arkui-256-V5

分享
微博
QQ
微信
回复
2024-12-24 20:00:45
相关问题
HarmonyOS @State可以修饰对象数组
353浏览 • 1回复 待解决
HarmonyOS @state可以修饰对象数组
340浏览 • 1回复 待解决
@State 修饰变量值改变,界面不刷新
2106浏览 • 1回复 待解决
HarmonyOS 数组对象数据刷新
466浏览 • 1回复 待解决
ForEach数组发生改变UI刷新
1230浏览 • 1回复 待解决
HarmonyOS LazyForEach不会更新@State
474浏览 • 1回复 待解决