请问如何优化这个存在异步逻辑的滚动事件监听函数?

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 来回横跳。

阅读 2.1k
1 个回答
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);
  }
},
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏