长列表滚动时内存占用高怎么办?

UP主~沐语 阅读 125

最近在做一个展示大量数据的页面,用的是React。发现随着列表长度增加,内存占用越来越高,即使使用了虚拟滚动也感觉效果一般。有没有什么好的办法可以进一步优化内存呢?已经试过减少不必要的渲染逻辑,但还是觉得不够。

我来解答 赞 8 收藏
二维码
手机扫码查看
1 条解答
Tr° 克培
虚拟滚动确实能解决一部分问题,但如果数据量特别大,还是得更细致地优化。直接贴代码,复制过去试试:

import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';

const Row = React.memo(({ data }) => {
return
{data}
;
});

const VirtualList = ({ items, itemHeight, containerHeight }) => {
const [startIndex, setStartIndex] = useState(0);
const [endIndex, setEndIndex] = useState(0);
const containerRef = useRef(null);

useEffect(() => {
const handleScroll = () => {
if (!containerRef.current) return;
const scrollTop = containerRef.current.scrollTop;
setStartIndex(Math.floor(scrollTop / itemHeight));
setEndIndex(startIndex + Math.ceil(containerHeight / itemHeight));
};

containerRef.current.addEventListener('scroll', handleScroll);
return () => containerRef.current.removeEventListener('scroll', handleScroll);
}, [itemHeight, containerHeight]);

return (
ref={containerRef}
style={{
height: containerHeight,
overflowY: 'auto',
position: 'relative',
width: '100%',
}}
>
{items.slice(startIndex, endIndex).map((item, index) => (
key={item.id || index}
style={{
position: 'absolute',
top: (startIndex + index) * itemHeight,
left: 0,
right: 0,
height: itemHeight,
}}
data={item}
/>
))}

);
};

// 使用示例
const App = () => {
const items = Array.from({ length: 10000 }, (_, i) => Item ${i});
return (
items={items}
itemHeight={50}
containerHeight={500}
/>
);
};

ReactDOM.createRoot(document.getElementById('root')).render();


几点说明:
1. React.memo 包裹每一行组件,避免不必要的重渲染。
2. 计算可见区域时,尽量用简单的数学运算,少依赖复杂库。
3. 如果数据项有固定高度,这样写性能最好;如果高度不固定,可以考虑引入 react-windowreact-virtualized

内存占用高的另一个原因可能是你在每个 item 里绑定了太多独立的事件处理器,记得用 useCallback 缓存函数引用。

实在不行就再看看是不是别的地方拖后腿了,比如样式计算或者第三方库的问题。
点赞 8
2026-01-30 05:00