用 react-window 实现动态高度列表

解读

在国内一线/二线大厂的面试中,“长列表性能优化”是前端性能方向的高频考点。
react-window 作为社区主流的
虚拟滚动(Virtual Scrolling)方案,默认只支持固定高度
(FixedSizeList)。
真实业务场景(如微博 Feed、小红书笔记、商品评价)往往高度由内容决定,需要动态测量并缓存,否则会出现白屏、跳动、滚动条抖动等体验问题。
面试官重点考察:

  1. 是否理解虚拟滚动原理(只渲染可视区 + 缓冲区)
  2. 能否正确使用 VariableSizeList 并自定义 itemSize 索引函数
  3. 是否掌握动态测量 DOM 高度的套路(ResizeObserver、ref 回调、缓存策略)
  4. 是否考虑缓存失效与更新机制(新增/删除/排序时清空或局部更新缓存)
  5. 是否给出性能边界(最大列表长度、内存占用、SSR 兼容性)

知识点

  • 虚拟滚动核心概念:渲染窗口(overscan)、起始索引(startIndex)、结束索引(endIndex)
  • VariableSizeList API:estimatedItemSize、itemSize(index)、ref.resetAfterIndex
  • 动态高度测量:
    – ref 回调 + getBoundingClientRect(兼容性好,需防抖)
    – ResizeObserver(精度高,需 polyfill 老浏览器)
  • 缓存策略:Map<index, number> 或 Array<number>,O(1) 读取
  • 缓存失效:数据增删改后调用 resetAfterIndex({index: 0, shouldForceUpdate: true})
  • React 18 并发特性:配合 startTransition 避免测量过程阻塞用户输入
  • 服务端渲染注意:estimatedItemSize 必须与首屏平均高度一致,防止 hydrate 错位
  • 性能红线:实测 10 k 条动态节点,内存占用 < 5 MB,主线程脚本执行 < 16 ms/帧

答案

import { VariableSizeList as List } from 'react-window';
import { useRef, useEffect, useState, useCallback, memo } from 'react';

const DynamicRow = memo(({ index, style, data }) => {
  const { list, cache, listRef } = data;
  const rowRef = useRef(null);

  useEffect(() => {
    if (rowRef.current) {
      const height = rowRef.current.getBoundingClientRect().height;
      const oldHeight = cache.current.get(index);
      if (oldHeight !== height) {
        cache.current.set(index, height);
        // 通知列表从当前索引开始重新计算
        listRef.current.resetAfterIndex(index);
      }
    }
  });

  return (
    <div style={style}>
      {/* 把真正的业务卡片塞进来 */}
      <div ref={rowRef}>
        <Card content={list[index]} />
      </div>
    </div>
  );
});

export default function DynamicList({ dataSource }) {
  const listRef = useRef(null);
  const cache = useRef(new Map()); // index -> height
  const [estimated] = useState(120); // 经验值,首屏平均高度

  const getItemSize = useCallback(
    index => cache.current.get(index) || estimated,
    [estimated]
  );

  const itemData = {
    list: dataSource,
    cache,
    listRef,
  };

  return (
    <List
      ref={listRef}
      height={600}                 // 可视区高度
      itemCount={dataSource.length}
      itemSize={getItemSize}
      itemData={itemData}
      overscanCount={2}            // 缓冲区,减少白屏
    >
      {DynamicRow}
    </List>
  );
}

关键点说明

  1. cache 用 Map 存储已测量高度,O(1) 查询;未命中时回退到 estimated 避免跳动。
  2. resetAfterIndex 只让列表从指定索引重新累加,避免全表重排。
  3. memo 包裹 DynamicRow,防止父组件状态变化导致整表重渲染。
  4. 若数据增删,父组件在 useEffect 中调用 cache.current.clear() 并 listRef.current.resetAfterIndex(0),保证缓存一致性。
  5. 若需要响应窗口宽度变化(图文混排换行),外层再包一层 ResizeObserver,监听容器宽度变化后清空缓存并重新测量。

拓展思考

  1. 超大列表(>100 k) 如何降低内存?
    采用 LRU 缓存 限制 Map 容量,只保留可视区前后 1 k 条记录;超出部分再次测量。
  2. 分页加载 + 动态高度 如何平滑衔接?
    在 onItemsRendered 中判断接近末尾时请求下一页,数据返回后追加到尾部并调用 resetAfterIndex(oldLastIndex),避免从头计算。
  3. React 18 的 Suspense 流式渲染 能否结合?
    可以。每行包裹 <Suspense fallback={<Skeleton />}>, 骨架屏高度写入 cache,真实组件渲染完再替换,保证滚动条不抖动。
  4. 兼容性要求 IE11 如何处理 ResizeObserver?
    引入 resize-observer-polyfill 并在打包时做 differential loading,现代浏览器走原生,老浏览器走 polyfill,体积增加 < 4 kB。
  5. 与 React-Virtualized 差异?
    react-window 是重写版,移除了 HOC 与冗余功能,包体积减少 70 %;若需要 CellMeasurer 自动测量,可自己实现或直接用社区封装 react-window-infinite-loader + VariableSizeList,面试时可主动提及,体现社区跟进能力。