如何阻止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> ); }
关键说明:
- 状态缓存:
initialWidth状态只会在组件首次渲染时被赋值,后续窗口尺寸变化时不会再更新,确保始终使用首次计算的宽度。 - 避免无效重渲染:移除了原代码中随机生成的
key,因为随机key会导致组件频繁销毁重建,影响性能,这里不需要额外的key来触发重渲染。 - 兜底处理:
initialWidth || width确保在首次渲染时(状态还未更新)能正常获取到当前宽度值。
内容的提问来源于stack exchange,提问作者yeln
相关产品推荐
相关产品推荐

