HarmonyOS @State修饰的数组内部的值变化了,怎么刷新UI?

​pageDatas是一个@State修饰的复杂对象数组,当修改数组中的某个值时UI不会变化吗?

是不是只有基本数据类型值改变时UI才会修改?如果是这样,应该怎么修改UI呢?

试过用DataSource的resetData也不行,首页用Swiper,获取网络数据后用resetData后是UI是有变化的,为什么这里不行。​

HarmonyOS @State修饰的数组内部的值变化了,怎么刷新UI?-鸿蒙开发者社区

HarmonyOS
2024-11-27 09:43:47
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

​要改变数组中对象的值需要用 @Observed和@ObjectLink,装饰器说明:对象数组是一种常用的数据结构。以下示例展示了数组对象的用法。

示例:​

@Component 
struct ViewA { 
  // 子组件ViewA的@ObjectLink的类型是ClassA 
  @ObjectLink a: ClassA; 
  label: string = 'ViewA1'; 
  build() { 
    Row() { 
      Button(`ViewA [${this.label}] this.a.c = ${this.a.c} +1`) 
        .onClick(() => { 
          this.a.c += 1; 
        }) 
    } 
  } 
} 
@Entry 
@Component 
struct ViewB { 
  // ViewB中有@State装饰的ClassA[] 
  @State arrA: ClassA[] = [new ClassA(0), new ClassA(0)]; 
  build() { 
    Column() { 
      ForEach(this.arrA, 
        (item: ClassA) => { 
          ViewA({ label: `#${item.id}`, a: item }) 
        }, 
        (item: ClassA): string => item.id.toString() 
      ) 
      // 使用@State装饰的数组的数组项初始化@ObjectLink,其中数组项是被@Observed装饰的ClassA的实例 
      ViewA({ label: `ViewA this.arrA[first]`, a: this.arrA[0] }) 
      ViewA({ label: `ViewA this.arrA[last]`, a: this.arrA[this.arrA.length-1] }) 
      Button(`ViewB: reset array`) 
        .onClick(() => { 
          this.arrA = [new ClassA(0), new ClassA(0)]; 
        }) 
      Button(`ViewB: push`) 
        .onClick(() => { 
          this.arrA.push(new ClassA(0)) 
        }) 
      Button(`ViewB: shift`) 
        .onClick(() => { 
          this.arrA.shift() 
        }) 
      Button(`ViewB: chg item property in middle`) 
        .onClick(() => { 
          this.arrA[Math.floor(this.arrA.length / 2)].c = 10; 
        }) 
      Button(`ViewB: chg item property in middle`) 
        .onClick(() => { 
          this.arrA[Math.floor(this.arrA.length / 2)] = new ClassA(11); 
        }) 
    } 
  } 
}
  • 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.
分享
微博
QQ
微信
回复
2024-11-27 14:51:13


相关问题
HarmonyOS @State可以修饰对象数组
545浏览 • 1回复 待解决
HarmonyOS @state可以修饰对象数组
517浏览 • 1回复 待解决
@State 修饰变量值改变,界面不刷新
2329浏览 • 1回复 待解决
IF条件变化UI刷新
1231浏览 • 1回复 待解决