在 OpenHarmony(ArkUI) 中,“ListView”通常指 List + ForEach / LazyForEach 的使用场景。List 本身已经做了不少优化,但在数据量大、布局复杂时仍需要主动优化。下面从核心原则 → 具体优化手段 → 示例代码系统说明。
List 必须使用 LazyForEach,而不是 ForEach
ForEach:一次性创建所有子项(卡顿、内存高)LazyForEach:只创建可视区域 + 缓冲区的子项 ✅List() {
LazyForEach(this.dataSource, (item) => {
ListItem() {
MyItemView({ item: item })
}
}, item => item.id)
}
✅ 要求:
IDataSourceclass MyDataSource implements IDataSource {
private list: Item[] = []
totalCount(): number {
return this.list.length
}
getData(index: number): Item {
return this.list[index]
}
registerDataChangeListener() {}
unregisterDataChangeListener() {}
}
❌ 不要在 getData 里 new 对象
✅ 数据提前准备好
List() {
...
}
.height('100%')
.width('100%')
❌ List 放在未限定高度的 Column 中
✅ 父容器必须有明确高度
优化建议:
Stack 多层叠加Image 的 objectFitListItem() {
Row() {
Image(item.icon).width(40).height(40)
Text(item.name).fontSize(14)
}
}
List() {
LazyForEach(...)
}
.cachedCount(5)
✅ 使用缩略图
✅ 使用 .syncLoad(false)(默认)
✅ 大图异步加载
Image(item.url)
.width(80)
.height(80)
.objectFit(ImageFit.Cover)
❌ 这样会全局刷新:
@State list: Item[] = []
✅ 使用 @Observed + @ObjectLink 或局部状态
reuseId(OpenHarmony 4.0+)ListItem()
.reuseId('myItem')
✅ 节点复用,减少创建销毁
| 问题 | 原因 | 解决 |
|---|---|---|
| 滑动卡顿 | ForEach | LazyForEach |
| 内存暴涨 | 全量创建 | 懒加载 |
| 白屏 | cachedCount 太小 | 增加 |
| 列表跳动 | key 不稳定 | 唯一 key |
| 滑动冲突 | 高度不明确 | 限定高度 |
List() {
LazyForEach(this.dataSource, (item) => {
ListItem() {
Row() {
Image(item.icon).width(40).height(40)
Text(item.title).fontSize(14)
}
.padding(10)
}
.reuseId('item')
}, item => item.id)
}
.cachedCount(5)
.height('100%')
.width('100%')
你可以直接贴 你的 List 代码或报错信息。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。