文档开发者中心
我的
|

HarmonyOS 5

数据管理

为什么给ArrayList添加数据的时候,不能触发UI刷新

已解决
收起
自动换行
深色代码主题
复制
struct TestPage {
  @State list:ArrayList<string> = new ArrayList();
  // @State list:string[] =[];
  aboutToAppear(): void {
    for (let index = 0; index < 5; index++) {
      this.list.add('index:'+index)
      // this.list.push('index:'+index)

    }
  }

  build() {
    Column() {
      List(){
        ForEach(this.list.convertToArray(),(item:string)=>{
          // ForEach(this.list,(item:string)=>{
          ListItem(){
            Text(item).fontColor(Color.Red).backgroundColor(Color.Pink).width('100%')
          }
        })
      }
      Button('添加').onClick(()=>{
        this.list.add('66666')
        // this.list.push('index:6666')
        promptAction.showToast({
          message:this.list.length+""
        })
      })
    }.width('100%')
    .height('100%')

  }
}
点赞
收藏
回复
3
分享
举报
浏览320 发布于2024-09-24 07:48广东
全部评论
最多点赞
最新发布
最早发布
|
采纳答复

建议用Array去替代ArrayList, 参考代码如下

收起
自动换行
深色代码主题
复制
 @State list: Array<string> = new Array();
  aboutToAppear(): void {
    for (let index = 0; index < 5; index++) {
      this.list.push('index:' + index)
    }
  }

  build() {
    Column() {
      List() {
        ForEach(this.list, (item: string) => {
          ListItem() {
            Text(item).fontColor(Color.Red).backgroundColor(Color.Pink).width('100%')
          }
        })
      }.width('100%')

      Button('添加').onClick(() => {
        this.list.push('1');
        promptAction.showToast({
          message: this.list.length + ""
        })

      })
    }.width('100%')
    .height('100%')
  }
3楼回复于2024-09-24 10:27 来自广东
2楼回复于2024-09-24 08:36 来自广东

在class ArrayList的add方法里面重新返回一个实力,参考如下

收起
自动换行
深色代码主题
复制
class ArrayList<T> {
  private items: T[] = [];
  add(item: T): ArrayList<T> {
    const newList = new ArrayList<T>();
    newList.items = [...this.items, item];
    return newList;
  }
  convertToArray(): T[] {
    return this.items;
  }
  length(): number {
    return this.items.length;
  }
}
1楼回复于2024-09-24 08:20 来自上海
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。