使用 List 构建动态数据列表:懒加载、分页、空状态处理实战 HarmonyOS 5.0.0 或以上
·
适配版本:HarmonyOS 5.0.0 或以上
阅读目标:掌握动态列表的构建方法,理解懒加载与分页加载机制,学会处理空数据和加载状态
📦 一、ArkUI 中的列表组件核心
HarmonyOS 提供以下组件用于构建列表:
| 组件 | 用途说明 |
|---|---|
List |
用于渲染动态或固定长度的滚动列表 |
ListItem |
每一项的容器,支持点击、样式、分隔线等 |
ForEach |
循环遍历数组生成 UI 元素 |
Scroll |
用于非列表结构的滚动容器 |
🧪 二、基本使用:构建一个静态列表
@Entry
@Component
struct StaticListDemo {
items: string[] = ['语文', '数学', '英语']
build() {
List() {
ForEach(this.items, (item) => {
ListItem() {
Text(item).fontSize(18).padding(12)
}
}, item => item)
}
}
}
🚀 三、动态加载 + 懒加载分页实战
@Entry
@Component
struct DynamicList {
@State list: string[] = []
@State loading: boolean = false
@State finished: boolean = false
page: number = 1
aboutToAppear() {
this.loadData()
}
async loadData() {
if (this.loading || this.finished) return
this.loading = true
// 模拟异步请求分页数据
await new Promise(resolve => setTimeout(resolve, 1000))
const newItems = Array.from({ length: 10 }, (_, i) => `第${(this.page - 1) * 10 + i + 1}项`)
if (newItems.length === 0) {
this.finished = true
} else {
this.list = [...this.list, ...newItems]
this.page++
}
this.loading = false
}
build() {
List() {
ForEach(this.list, (item) => {
ListItem() {
Text(item).fontSize(16).padding(10)
}
}, item => item)
if (this.loading) {
ListItem() {
Text('加载中...').fontColor('#888').padding(10)
}
}
if (this.finished) {
ListItem() {
Text('已经到底了').fontColor('#aaa').padding(10)
}
}
}
.onScrollIndex((index: number) => {
if (index >= this.list.length - 1) {
this.loadData()
}
})
}
}
🧩 四、空状态占位处理
if (this.list.length === 0 && !this.loading) {
Column() {
Image($r('app.media.empty'))
.width(100)
.height(100)
Text('暂无数据').fontSize(16).fontColor('#888')
}.padding(40).alignItems(HorizontalAlign.Center)
}
✅ 可在数据为空时展示提示图文,提升用户体验。
🎯 五、列表分页与滚动加载策略
| 策略类型 | 实现方式 | 场景适用 |
|---|---|---|
| 懒加载(无限滚动) | 搭配 onScrollIndex 检测临界点 |
新闻流、评论、商品列表 |
| 按页请求 + 分页按钮 | 用户主动点击“加载更多” | 课程目录、日志记录 |
| 首次请求 + 局部刷新 | 页面展示前一次性拉取全部数据 | 分类页、设置项 |
✅ 六、小结
| 技术点 | 应用说明 |
|---|---|
List 与 ListItem |
构建滚动式可变列表结构 |
| 懒加载分页 | 结合 onScrollIndex 和 @State 控制加载流程 |
| 空状态处理 | 无数据时通过占位图文提升 UX |
| 请求节流/加载控制 | 使用 loading + finished 双变量进行判断 |
📘 下一篇预告
第24篇|表单组件使用与输入处理:TextInput、Slider、Toggle 实战封装
将演示表单输入的响应式绑定、字段校验与封装技巧,构建登录表单或信息提交模块。
更多推荐



所有评论(0)