请问如何优化这个存在异步逻辑的滚动事件监听函数?
async _handleBrandListScroll() {
const { ids, mainScrollerOffset } = this.data;
let indexs: number[] = [];
for (const id of ids) {
const [[{ top: rectTop }]] = await queryBoundingClient(this, id);
if (typeof rectTop !== 'number') continue;
if (rectTop <= mainScrollerOffset) {
const idIndexs = getIdIndexs(id);
if (!_.isUndefined(idIndexs)) {
indexs = idIndexs;
}
} else {
break;
}
}
const [mainIndex, subIndex] = indexs;
if (this.data.currentLeftTabIndex !== mainIndex) {
this.setData({ currentLeftTabIndex: mainIndex });
this.updateCurrentTopTabList(mainIndex);
}
if (this.data.currentTopTabIndex !== subIndex) {
this.setData({ currentTopTabIndex: subIndex });
this.updateTopTabsScrollLeft(subIndex);
}
},
主要问题是 queryBoundingClient 是异步返回结果的(在微信小程序环境中),导致 _handleBrandListScroll 的 throttle 无效,结果 indexs 不准。体现在视图上就是,滑动过快时当前选中的 tab 来回横跳。
回复
1个回答
test
2024-06-27
async _handleBrandListScroll() {
const { ids, mainScrollerOffset } = this.data;
let indexs: number[] = [];
// Step 1: 批量处理异步请求
const rectTops = await Promise.all(ids.map(id => queryBoundingClient(this, id)));
for (let i = 0; i < rectTops.length; i++) {
const [[{ top: rectTop }]] = rectTops[i];
if (typeof rectTop !== 'number') continue;
if (rectTop <= mainScrollerOffset) {
const idIndexs = getIdIndexs(ids[i]);
if (!_.isUndefined(idIndexs)) {
indexs = idIndexs;
}
} else {
break;
}
}
const [mainIndex, subIndex] = indexs;
if (this.data.currentLeftTabIndex !== mainIndex) {
this.setData({ currentLeftTabIndex: mainIndex });
this.updateCurrentTopTabList(mainIndex);
}
if (this.data.currentTopTabIndex !== subIndex) {
this.setData({ currentTopTabIndex: subIndex });
this.updateTopTabsScrollLeft(subIndex);
}
},
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容