在无限加载列表中如何回收 DOM 并保留滚动位置

解读

国内一线/二线公司面试中,这道题出现的频率极高,核心考察点不是“无限加载”本身,而是“性能优化”与“滚动体验”两大维度。

  1. 性能:移动端 4G、低端安卓机、企业微信/钉钉内嵌 WebView 极易因 DOM 节点过多而掉帧,必须回收。
  2. 体验:回收后滚动条高度突变、定位漂移,会被用户直接感知;面试官希望听到“滚动条不跳、数据不闪、回退不白屏”的完整闭环方案。
  3. 边界:网络抖动、快速滚动、列表项高度动态(图文、富文本、视频)、SSR 首屏、React 18 Concurrent 特性,都要覆盖。

知识点

  1. 虚拟滚动(Windowing)核心公式
    • 可视区起始索引 startIndex = Math.floor(scrollTop / itemEstimatedHeight)
    • 可视区节点数 visibleCount = Math.ceil(clientHeight / itemEstimatedHeight) + buffer
    • 渲染区间 = [startIndex – buffer, startIndex + visibleCount + buffer]
  2. 滚动位置保留三件套
    • 滚动条高度:用“占位元素”(div spacer)撑开总高度,高度 = sum(itemHeight) 或 estimatedHeight * totalCount。
    • 滚动偏移:在回收节点后,通过 transform: translateY(offset) 或 paddingTop 补偿被卸载节点的高度,保证 scrollTop 不变。
    • 浏览器原生行为:push/replace 时把 scrollTop 写入 history.state,回退时恢复;或使用 IntersectionObserver 记录锚点元素。
  3. React 实现细节
    • 自定义 Hooks:useVirtualList(返回 startIndex、endIndex、offsetY)、useItemHeight(动态测量、缓存、LRU 淘汰)。
    • 时间切片:React 18 startTransition 把 setState 标记为非紧急,避免快速滚动时抢占输入事件。
    • 内存回收:unmount 时清除 heightCache 中超出“三屏”外的键,防止长列表内存泄漏。
  4. 性能指标
    • FPS:Chrome DevTools Rendering 面板,滚动期间保持 55+ fps。
    • FID:首次输入延迟 < 100 ms,避免在 scroll 回调里做同步 JSON.parse。
    • LCP:首屏仍需秒开,SSR 时只渲染首屏真实节点,剩余用占位。

答案

“我最近在项目里用 React 18 + TypeScript 做了一套‘动态高度虚拟列表’,线上 10 万条数据,低端安卓机也不会掉帧,滚动位置在前进/回退时完全保持,思路分三步:

  1. 结构
    外层固定高度的容器 position: relative; overflow: auto;
    内部一个总占位 div(spacer)撑起真实总高;
    中间一块渲染区 div(viewport)使用 transform: translateY(offset) 定位。

  2. 高度测量与缓存
    首次渲染用 estimatedHeight=60px 做初始值;
    每个列表项套上 Ref,在 useLayoutEffect 里读取 getBoundingClientRect().height,写入 Map<id, height>;
    同时维护一个前缀和数组 prefixSum,支持 O(1) 查询任意区间总高;
    为了防止 Map 无限增长,监听滚动方向,只保留“当前可视区前后各三屏”的缓存,其余 delete。

  3. 滚动位置保留
    a. 滚动过程中实时记录 scrollTop 到 history.replaceState({ scrollTop }, ''),用户点击详情页再返回时,在 useEffect 里读取 history.state.scrollTop 并赋值给 container.scrollTop;
    b. 如果列表项高度动态变化导致总高变化,用 prefixSum 重新计算 spacer 高度,但保持 scrollTop 不变,浏览器不会跳动;
    c. 对于“视频卡片”这种高度异步加载(封面加载完才撑开)的场景,用 ResizeObserver 监听尺寸变化,增量更新缓存并修正 spacer,修正过程包裹在 startTransition 里,避免掉帧。

  4. 代码骨架(现场手写)

const Row = memo(({ id, measure }: { id: string; measure: (el: HTMLDivElement) => void }) => {
  const ref = useRef<HTMLDivElement>(null);
  useLayoutEffect(() => { if (ref.current) measure(ref.current); }, [measure]);
  return <div ref={ref}>内容 {id}</div>;
});

function VirtualList({ total }) {
  const [cache, setCache] = useState(() => new Map<string, number>());
  const containerRef = useRef<HTMLDivElement>(null);
  const [scrollTop, setScrollTop] = useState(0);
  const clientHeight = containerRef.current?.clientHeight || 600;

  const prefixSum = useMemo(() => {
    const arr = [0];
    for (let i = 0; i < total; i++) {
      arr.push(arr[arr.length - 1] + (cache.get(String(i)) || 60));
    }
    return arr;
  }, [cache, total]);

  const findIndex = (y: number) => {
    let l = 0, r = total;
    while (l < r) {
      const m = (l + r) >> 1;
      if (prefixSum[m] < y) l = m + 1; else r = m;
    }
    return Math.max(0, l - 1);
  };

  const startIndex = findIndex(scrollTop);
  const endIndex = Math.min(total - 1, findIndex(scrollTop + clientHeight) + 3);

  const measure = useCallback((el: HTMLDivElement) => {
    const h = el.getBoundingClientRect().height;
    const id = el.dataset.id!;
    setCache(prev => {
      if (prev.get(id) === h) return prev;
      const next = new Map(prev);
      next.set(id, h);
      return next;
    });
  }, []);

  useEffect(() => {
    const el = containerRef.current!;
    const onScroll = () => setScrollTop(el.scrollTop);
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, []);

  // 恢复滚动位置
  useEffect(() => {
    const saved = history.state?.scrollTop;
    if (saved && containerRef.current) {
      containerRef.current.scrollTop = saved;
    }
  }, []);

  const offsetY = prefixSum[startIndex];
  const spacerHeight = prefixSum[total] - prefixSum[endIndex + 1];

  return (
    <div ref={containerRef} style={{ height: '100vh', overflow: 'auto' }}>
      <div style={{ height: prefixSum[total] }}>
        <div style={{ transform: `translateY(${offsetY}px)` }}>
          {Array.from({ length: endIndex - startIndex + 1 }, (_, i) => {
            const idx = startIndex + i;
            return <Row key={idx} id={String(idx)} measure={measure} data-id={idx} />;
          })}
        </div>
        <div style={{ height: spacerHeight }} />
      </div>
    </div>
  );
}
  1. 结果
    线上实测 10 万条数据,DOM 节点恒定在 30 个左右,滚动全程 58 fps;
    用户前进到详情页再点返回,列表滚动条分毫不差,首屏 LCP 1.4 s,完全满足业务指标。”

拓展思考

  1. 反向无限加载(聊天窗口往上翻历史)如何复用同一套虚拟滚动?
    需要把 prefixSum 改成双向链表或前后两段数组,滚动到顶部时动态在头部插入占位,同时把 scrollTop 修正为“旧顶部高度 + 新加载高度”,避免跳动。

  2. 与 React Concurrent 的深度结合
    使用 useDeferredValue 把“快速滚动时的渲染索引”变成低优更新,用户停止滚动 200 ms 后再渲染真实内容,可进一步降低掉帧概率;
    配合 useId 为每条数据生成稳定 key,避免 Concurrent 双缓冲阶段出现闪烁。

  3. 跨端场景
    React Native FlatList 已内置 getItemLayout 与 onScrollToIndexFailed,但高度必须提前知道;
    若高度动态,可借鉴 Web 的 onLayout 测量思路,把测量结果通过 JSI 写入 C++ 缓存,实现 Native 层回收,性能比 JS 层更高。