前端虚拟列表实现:优化万级数据渲染性能
为什么需要虚拟列表
在大型项目中,一次性渲染大量列表项(如 5000+ 选项)会导致页面卡死。例如,一个下拉列表包含 10000 个数据项时,直接渲染会严重消耗浏览器资源。
错误示例
// 反面教材:一次性渲染所有数据
function BigList({ items }) {
return (
<ul style={{ height: '400px', overflow: 'auto' }}>
{items.map(item => (
<li key={item.id} style={{ height: '50px' }}>
{item.name}
</li>
))}
</ul>
);
}
// 使用
// <BigList items={Array.from({ length: 10000 }, (_, i) => ({ id: i, name: `Item ${i}` }))} />
渲染 10000 个 DOM 节点会显著降低页面性能。
实现方案
1. 基础虚拟列表实现
// 正确姿势:基础虚拟列表
import { useState, useRef, useMemo, useCallback } from 'react';
function VirtualList({ items, itemHeight, containerHeight }) {
const [scrollTop, setScrollTop] = useState(0);
const containerRef = useRef(null);
// 计算可见区域
visibleCount = .(containerHeight / itemHeight);
totalHeight = items. * itemHeight;
startIndex = .(scrollTop / itemHeight);
endIndex = .(startIndex + visibleCount + , items.);
visibleItems = ( {
items.(startIndex, endIndex);
}, [items, startIndex, endIndex]);
offsetY = startIndex * itemHeight;
handleScroll = ( {
(e..);
}, []);
(
);
}
() {
items = .({ : }, ({ : i, : }));
;
}


