设置一个中间变量用来接收更新的值,在onDidScroll回调中判断当前List滑动状态,如果是滑动时,数据只更新到中间变量,不刷新到List数据源,滑动停止时把中间变量的数据刷新到数据源上。非滑动时,更新到中间变量后,立即更新进List数据源,从而实现在List滑动期间仅更新数据而不触发组件渲染。
@Entry
@ComponentV2
struct ListScrollDemo {
@Local dataArr: Array<string> = [];
@Local num: number = 0;
@Local temp: string = '';
@Local isScroll: boolean = false;
@Monitor('temp')
onStrChange() {
// 非滚动状态,把状态变量更新到数据源
if (!this.isScroll) {
this.dataArr[5] = this.temp;
}
}
aboutToAppear(): void {
for (let i = 0; i < 30; i++) {
this.dataArr.push(`data_${i}`);
}
setInterval(() => {
// 模拟数据刷新
this.temp = JSON.stringify(this.num);
this.num++;
}, 1000);
}
build() {
List() {
Repeat<string>(this.dataArr)
.each((ri: RepeatItem<string>) => {
ListItem() {
Text(ri.item)
.width('100%')
.height(60)
.fontSize(20)
.textAlign(TextAlign.Center)
.backgroundColor(0xFFFFFF)
}
})
}
.height('100%')
.width('100%')
.onDidScroll((scrollOffset: number, scrollState: ScrollState) => {
console.info(`scrollOffset: ${scrollOffset}`);
if (scrollState === 0) {
this.isScroll = false;
} else {
this.isScroll = true;
}
})
.onScrollStop(() => {
// 滚动停止时,将最新中间变量的值更新到数据源
this.dataArr[5] = this.temp;
})
}
}