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
  }
}
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可以修饰对象数组
149浏览 • 1回复 待解决
HarmonyOS @state可以修饰对象数组
163浏览 • 1回复 待解决
@State 修饰变量值改变,界面不刷新
1881浏览 • 1回复 待解决
ForEach数组发生改变UI刷新
942浏览 • 1回复 待解决
HarmonyOS 数组对象数据刷新
239浏览 • 1回复 待解决
HarmonyOS LazyForEach不会更新@State
276浏览 • 1回复 待解决