HarmonyOS list 如何对list进行数据修改时,同步到相应的UI?

场景:PageA,有一个列表 listA<Bean\> ,设置如下:

PageA{
  build() {
    List() {
      ForEach(this.listA, (item: Bean, index: number) => {
        ListItem() {
          ViewB({ info: item })
        }
      }, (item: Bean, index: number) => 'id_' + index)
    }
  }
}

ViewB{
  @Prop info:Bean
  //相关展示
}

当PageA对listA中的数据进行修改时发现,并没用同步到ViewB进行更新。

查询到@ObservedV2装饰器和@Trace装饰器:类属性变化观测 可能适用我当前场景,但是ViewB无法使用@Prop等装饰器接参,pageA也无法通过ViewB({ info: item }) 的方式将数据传递进去。

要怎么解决这个问题

阅读 533
1 个回答

可以参考ComponentV2的文档,因为V2中有自己的装饰器来替换v1之前的装饰器,写法有所不同,文档请参考: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-new-componentv2-V5

demo如下:

let nextId: number = 0;

@ObservedV2
class Arr {
  id: number = 0;
  @Trace numberArr: number[] = [];

  constructor() {
    this.id = nextId++;
    this.numberArr = [0, 1, 2];
  }
}

@ComponentV2
struct ViewA {
  @Param label: string = 'ViewA';
  @Param index: number = 0;
  @Param value: number = 0;

  build() {
    Column() {
      Text(`ViewA [${this.label}] 索引${this.index}-值${this.value}`)
        .margin(10)
        .textAlign(TextAlign.Center)
    }
  }
}


@Entry
@ComponentV2
struct Index {
  arr: Arr = new Arr();

  build() {
    Column() {
      ForEach(this.arr.numberArr, (item: number, index: number) => {
        ViewA({ label: '#1', index: index, value: item })
      })

      // 操作
      Flex({justifyContent: FlexAlign.SpaceBetween}) {
        Button('push')
          .onClick(() => {
            this.arr.numberArr.push(50);
          })
        Button('shift')
          .onClick(() => {
            this.arr.numberArr.shift();
          })
        Button('splice')
          .onClick(() => {
            this.arr.numberArr.splice(1, 0, 60);
          })
      }
      .padding({top: 24})
    }
    .width('100%')
    .height('100%')
    .padding(24)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进