ForEach数组发生改变。UI没刷新

在A页面创建自定义对象数组arr,ForEach循环渲染自定义组件,界面正常,A页面打开B页面后,在关闭B页面。在A页面的声明周期onPageShow中,把arr = [] 重新push对象,两次push对象基本一致,只是属性不同,UI不会发生改变。

HarmonyOS
2024-09-23 13:37:43
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

使用label作为key的话,因为重新赋值之后label没有发生变化,所以并没有刷新UI使用JSON.stringify绑定的key值是序列化之后的数组,因而value发生变化之后,UI会跟随刷新ForEach键值生成规则

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-rendering-control-foreach-V5

参考demo:

import router from '@ohos.router';  
  
class cs {  
  lable: string  
  value: string  
  
  constructor(lable: string, value: string) {  
    this.lable = lable;  
    this.value = value;  
  }  
}  
  
  
@Entry  
@Component  
struct ForEachTest {  
  @State message: string = 'Hello World';  
  @State arr: cs[] = []  
  num = 0  
  
  aboutToAppear(): void {  
    this.arr.push(new cs('name1', 'value1'))  
    this.arr.push(new cs('name2', 'value2'))  
    this.arr.push(new cs('name3', 'value3'))  
    console.log('arr',JSON.stringify(this.arr))  
  }  
  
  onPageShow(): void {  
    if (this.num != 0) {  
      this.arr = []  
      this.arr.push(new cs('name1', 'value1' + this.num))  
      this.arr.push(new cs('name2', 'value2' + this.num))  
      this.arr.push(new cs('name3', 'value3' + this.num))  
    }  
    this.num++  
  }  
  
  build() {  
    Column() {  
      ForEach(this.arr, (item: cs) => {  
        Row() {  
          Text(item.lable)  
          Blank()  
          Text(item.value)  
        }.width('100%').onClick(() => {  
          router.pushUrl({  
            url: "pages/Cs",  
          })  
        })  
      })  
    }  
    .height('100%')  
  }  
}
  • 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.
分享
微博
QQ
微信
回复
2024-09-23 17:21:14


相关问题
修改ForEach使用的数据对象,UI刷新
2948浏览 • 1回复 待解决
ForEach数组数据无法传输
6192浏览 • 1回复 待解决
HarmonyOS ForEach局部刷新
1322浏览 • 1回复 待解决
HarmonyOS 嵌套数组元素的UI刷新方案
1018浏览 • 1回复 待解决
HarmonyOS ForEach列表刷新问题
909浏览 • 1回复 待解决
HarmonyOS 数组对象数据刷新
838浏览 • 1回复 待解决
HarmonyOS ForEach创建的视图刷新问题
616浏览 • 1回复 待解决