温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

OpenHarmony ListView怎样刷新

发布时间:2026-10-10 15:23:02 来源:亿速云 阅读:89 作者:小樊 栏目:软件技术

在 OpenHarmony(ArkUI) 里,“ListView 刷新”通常指 数据变化后让列表重新渲染。不同开发方式(eTag / ArkTS)略有区别,下面按最常见场景说明。


一、ArkTS(声明式开发,推荐 ✅)

在 ArkTS 中,ListView 一般用 List + ForEach,刷新本质是状态驱动 UI。

1️⃣ 使用 @State 触发刷新(最常用)

@Entry
@Component
struct ListViewPage {
  @State listData: string[] = ['A', 'B', 'C']

  build() {
    Column() {
      Button('刷新数据')
        .onClick(() => {
          // 修改数据源即可刷新
          this.listData = ['A', 'B', 'C', 'D', 'E']
        })

      List() {
        ForEach(this.listData, (item: string) => {
          ListItem() {
            Text(item)
          }
        }, (item: string) => item)
      }
    }
  }
}

✅ 关键点

  • 必须改 @State 变量
  • 不能直接 listData.push()(不会触发刷新)
  • 正确方式:
    this.listData = [...this.listData, 'new']
    

2️⃣ 下拉刷新(Refresh 容器)

@Entry
@Component
struct RefreshList {
  @State listData: string[] = ['1', '2', '3']
  @State isRefreshing: boolean = false

  build() {
    Refresh({ refreshing: this.isRefreshing }) {
      List() {
        ForEach(this.listData, item => {
          ListItem() {
            Text(item)
          }
        })
      }
    }
    .onRefreshing(() => {
      // 模拟网络请求
      setTimeout(() => {
        this.listData = ['new1', 'new2', 'new3']
        this.isRefreshing = false
      }, 1000)
    })
  }
}

3️⃣ 局部刷新(提升性能)

如果只改某一项:

this.listData[index] = newValue
this.listData = [...this.listData]

或使用 @Observed + @ObjectLink(对象数组场景)


二、JS(类 Web 开发,兼容旧版本)

如果是 FA 模型(JavaScript):

this.listData = newData
this.$forceUpdate()

或:

this.listData.splice(0)
this.listData.push(...newData)

三、常见坑 ⚠️

❌ 直接修改数组不刷新
✅ 必须重新赋值

❌ key 不唯一
✅ ForEach 第三个参数必须唯一


四、总结

场景 方法
普通刷新 修改 @State 数据
下拉刷新 Refresh 组件
局部刷新 改数组 + 重新赋值
JS 项目 $forceUpdate()

如果你用的是 具体版本(如 OpenHarmony 3.2 / 4.0) 或 JS / ArkTS,可以告诉我,我给你更精准示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手