Communitygithub.com

YepAPI/无限滚动技能

实现基于游标的分页、IntersectionObserver 观察器、使用 @tanstack/react-virtual 的虚拟化列表以及滚动位置恢复。

无限滚动技能 是什么?

该技能为 AI 代理(如 Claude Code、Coder、Cursor)提供了实现高性能无限滚动列表的完整指南。它涵盖了四个关键领域:基于游标的分页(避免 offset 分页在数据插入/删除时产生的问题)、使用 IntersectionObserver 实现自动加载(在用户滚动到底部附近时预取数据)、使用 @tanstack/react-virtual 实现虚拟化(仅渲染可见的 DOM 节点,从而支持 1000+ 甚至 10000+ 项列表)、以及滚动位置恢复(通过 sessionStorage 在导航后记住用户位置)。技能提供了可直接使用的 React + TanStack Query 和 @tanstack/react-virtual 代码示例,包括空状态、加载骨架屏(非旋转器)以及“已到达列表末尾”指示器。该技能遵循现代前端最佳实践,避免了 offset 分页、客户端全量过滤后渲染以及缺失尽头指示器等常见反模式。适用于 React 生态下的无限列表、社交媒体 feed、大型数据表格等场景。

兼容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/YepAPI/skills/tree/HEAD/skills/infinite-scroll

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

无限滚动

规则

  • 基于游标的分页:使用最后一项的 ID 或时间戳作为游标——不要用偏移量,偏移量在插入/删除时会失效
  • IntersectionObserver 观察器:将观察器附加到列表底部的哨兵元素上——当元素可见时触发数据获取
  • 虚拟化:对于包含 1000+ 项的列表使用 @tanstack/react-virtual——只渲染当前可见的行到 DOM 中
  • 加载骨架屏:在获取下一页时在底部显示占位项——不要使用旋转器
  • “加载更多”按钮:作为备用方案提供,适用于偏好手动控制或网络较慢的用户
  • 滚动位置恢复:在导航前保存滚动位置,返回时恢复——使用 sessionStorage 或路由状态
  • 空状态:当列表中没有项时显示一条信息——不要显示空白页
  • 列表末尾:当 hasNextPage 为 false 时显示“你已经到达末尾”——停止观察器

模式

// 使用 React Query + IntersectionObserver 实现的无限滚动
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>
  );
}

// 针对 10k+ 项的虚拟化列表
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 的边距,以便在用户到达底部之前预取
  • 缺少列表末尾指示器——用户需要知道已经没有更多内容可加载

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

YepAPI/skills

WCAG 2.1 AA — semantic HTML, keyboard navigation, screen readers.

YepAPI/skills

Experiment setup, variant splitting, statistical significance, and feature flag integration.

YepAPI/skills

CRUD generators, data tables, user management, role-based access, and bulk operations.

YepAPI/skills

Monitor what ChatGPT and Gemini say about your brand using YepAPI.

YepAPI/skills

Queue workers with BullMQ/Inngest/Trigger.dev, job retries, dead letter queues, concurrency.

YepAPI/skills

Commander.js, interactive prompts with Clack, spinners, colors, config files, exit codes, and npm publishing.

YepAPI/skills

cmdk integration, Cmd+K trigger, fuzzy search, grouped actions, keyboard navigation, and dynamic action registration.

YepAPI/skills

Content planning with trend and sentiment data from YepAPI.

YepAPI/skills

Content calendar, keyword-driven planning, and content briefs.

YepAPI/skills

Theme switching with CSS variables, system preference detection, next-themes, and persistence.

YepAPI/skills

Threaded comments, @mentions, reactions, moderation queue, optimistic UI, and cursor pagination.

YepAPI/skills

Competitive analysis between domains using YepAPI.

YepAPI/skills

Layout grids, KPI cards, data tables with sorting/filtering, sidebar navigation, and responsive breakpoints.

YepAPI/skills

Data encryption — TLS everywhere, AES-256-GCM for PII, bcrypt passwords, encrypted backups.

YepAPI/skills

Chart patterns with Recharts/Nivo/D3, responsive containers, color scales, and accessibility.

YepAPI/skills

Drizzle schema definition, push vs migrate, type-safe queries, relations, transactions, and prepared statements.

YepAPI/skills

Upload handling, resize/compress, CDN delivery, blur placeholders, and next/image patterns.

YepAPI/skills

Local business and Google Maps research using YepAPI.

YepAPI/skills

Tenant isolation (row-level vs schema), subdomain routing, per-tenant config, and data partitioning.

YepAPI/skills

Chat UI components, streaming responses with AI SDK, context window management, and RAG patterns.

相关技能