You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止react-virtualized的AutoSizer在窗口动态调整时持续更新宽度?

解决react-virtualized的AutoSizer仅首次计算宽度的问题

要让AutoSizer只在页面首次加载或刷新时计算一次宽度,后续窗口尺寸变化不再更新,你可以通过React状态缓存首次获取的宽度值,具体实现步骤如下:

  • 用useState创建状态变量,专门存储首次加载时的容器宽度
  • 在AutoSizer的回调函数中,仅当状态为空时才更新宽度,后续始终使用缓存的首次值

修改后的完整代码如下:

import { useState } from 'react';
import {
  List,
  AutoSizer,
  CellMeasurer,
  CellMeasurerCache,
} from "react-virtualized";

function Result(props) {
  // 缓存首次加载的宽度,初始值为null
  const [initialWidth, setInitialWidth] = useState(null);
  
  ...
  return (
    <AutoSizer disableHeight>
      {({ width }) => {
        // 仅在首次获取到宽度时更新状态
        if (!initialWidth) {
          setInitialWidth(width);
        }
        // 优先使用缓存的首次宽度,初始加载时用当前width兜底
        const containerWidth = initialWidth || width;

        renderJustifiedLayoutGeometry();

        return (
          <div className="c-justified-grid" style={{ width: containerWidth }}>
            <List
              width={containerWidth}
              height={100}
              autoHeight={true}
              rowHeight={rowHeight}
              rowRenderer={renderRow}
              rowCount={new_LayoutGeometry.length}
              style={{ contain: "layout" }}
              overscanRowCount={3}
            />
          </div>
        );
      }}
    </AutoSizer>
  );
}

关键说明:

  1. 状态缓存:initialWidth状态只会在组件首次渲染时被赋值,后续窗口尺寸变化时不会再更新,确保始终使用首次计算的宽度。
  2. 避免无效重渲染:移除了原代码中随机生成的key,因为随机key会导致组件频繁销毁重建,影响性能,这里不需要额外的key来触发重渲染。
  3. 兜底处理:initialWidth || width确保在首次渲染时(状态还未更新)能正常获取到当前宽度值。

内容的提问来源于stack exchange,提问作者yeln

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 11:54:19