无限滚动
规则
- 基于游标的分页:使用最后一项的 ID 或时间戳作为游标——不要用偏移量,偏移量在插入/删除时会失效
- IntersectionObserver 观察器:将观察器附加到列表底部的哨兵元素上——当元素可见时触发数据获取
- 虚拟化:对于包含 1000+ 项的列表使用
@tanstack/react-virtual——只渲染当前可见的行到 DOM 中
- 加载骨架屏:在获取下一页时在底部显示占位项——不要使用旋转器
- “加载更多”按钮:作为备用方案提供,适用于偏好手动控制或网络较慢的用户
- 滚动位置恢复:在导航前保存滚动位置,返回时恢复——使用
sessionStorage 或路由状态
- 空状态:当列表中没有项时显示一条信息——不要显示空白页
- 列表末尾:当
hasNextPage 为 false 时显示“你已经到达末尾”——停止观察器
模式
import { useInfiniteQuery } from "@tanstack/react-query";
import { useRef, useEffect } from "react";
function InfiniteList() {
const sentinelRef = useRef<HTMLDivElement>(null);
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
queryKey: ["items"],
queryFn: ({ pageParam }) => fetchItems({ cursor: pageParam, limit: 20 }),
getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
initialPageParam: undefined as string | undefined,
});
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => { if (entries[0].isIntersecting && hasNextPage) fetchNextPage(); },
{ rootMargin: "200px" }
);
if (sentinelRef.current) observer.observe(sentinelRef.current);
return () => observer.disconnect();
}, [hasNextPage, fetchNextPage]);
const allItems = data?.pages.flatMap((page) => page.items) ?? [];
return (
<div>
{allItems.map((item) => <ItemCard key={item.id} item={item} />)}
{isFetchingNextPage && <LoadingSkeleton count={3} />}
{!hasNextPage && allItems.length > 0 && <p>你已经到达末尾</p>}
{allItems.length === 0 && !isFetchingNextPage && <EmptyState />}
<div ref={sentinelRef} />
</div>
);
}
import { useVirtualizer } from "@tanstack/react-virtual";
function VirtualList({ items }: { items: Item[] }) {
const parentRef = useRef<HTMLDivElement>(null);
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 64,
overscan: 5,
});
return (
<div ref={parentRef} style={{ height: "600px", overflow: "auto" }}>
<div style={{ height: `${virtualizer.getTotalSize()}px`, position: "relative" }}>
{virtualizer.getVirtualItems().map((virtualRow) => (
<div key={virtualRow.key} style={{
position: "absolute", top: 0, left: 0, width: "100%",
transform: `translateY(${virtualRow.start}px)`,
}}>
<ItemCard item={items[virtualRow.index]} />
</div>
))}
</div>
</div>
);
}
避免
- 基于偏移量的分页——插入/删除操作会改变所有偏移量,导致重复或缺失项
- 加载所有项后再在客户端过滤——只从服务器获取当前页面数据
- 渲染 10k+ DOM 节点——使用
@tanstack/react-virtual 只渲染可见行
- IntersectionObserver 不设置
rootMargin——添加 100-200px 的边距,以便在用户到达底部之前预取
- 缺少列表末尾指示器——用户需要知道已经没有更多内容可加载