Communitygithub.com

ComeOnOliver/skillshub

现代React UI模式,涵盖加载状态、错误处理和数据处理。适用于构建UI组件、处理异步数据或管理UI状态。

skillshub 是什么?

这个技能提供了构建健壮React UI的全面模式,重点在于加载状态、错误处理和优化的数据获取。核心原则包括:绝不展示过时的UI,仅在无数据时显示加载指示器;始终向用户呈现错误,绝不静默吞没异常;通过乐观更新实现即时响应;以及采用渐进式展示和优雅降级策略。涵盖的具体模式包括:加载状态决策树(错误→错误状态,加载且无数据→加载指示器→数据展示)、骨架屏与旋转器的选择指南、错误处理层级(内联错误→Toast通知→错误横幅→全屏错误)、按钮禁用与加载状态的最佳实践(异步操作期间必须禁用触发器)、以及不同类型(搜索无结果、列表无条目)的空状态组件设计。最后附有UI状态检查清单,确保每个组件都妥善处理了错误、加载和空状态。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/chriswiles/react-ui-patterns

在你喜欢的 AI 中提问

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

文档

React UI 模式

核心原则

  1. 永不显示过时 UI - 仅在真正加载时显示加载旋转器
  2. 始终暴露错误 - 用户必须知道何时发生故障
  3. 乐观更新 - 让 UI 感觉瞬间响应
  4. 渐进式披露 - 随着内容可用逐步展示
  5. 优雅降级 - 部分数据总比没有数据好

加载状态模式

黄金法则

仅在没有数据可显示时显示加载指示器。

// 正确 - 仅在没有数据时显示加载
const { data, loading, error } = useGetItemsQuery();

if (error) return <ErrorState error={error} onRetry={refetch} />;
if (loading && !data) return <LoadingState />;
if (!data?.items.length) return <EmptyState />;

return <ItemList items={data.items} />;
// 错误 - 即使有缓存数据也显示旋转器
if (loading) return <LoadingState />; // 刷新时会闪烁!

加载状态决策树

是否有错误?
  → 是:显示带重试选项的错误状态
  → 否:继续

是否正在加载且没有数据?
  → 是:显示加载指示器(旋转器/骨架屏)
  → 否:继续

是否有数据?
  → 有,且包含项目:显示数据
  → 有,但为空:显示空状态
  → 无:显示加载(兜底)

骨架屏 vs 旋转器

使用骨架屏的场景使用旋转器的场景
已知内容形状未知内容形状
列表/卡片布局模态框操作
初始页面加载按钮提交
内容占位符内联操作

错误处理模式

错误处理层级

1. 内联错误(字段级)→ 表单验证错误
2. Toast 通知 → 可恢复错误,用户可以重试
3. 错误横幅 → 页面级错误,数据仍可部分使用
4. 全屏错误 → 不可恢复,需要用户操作

始终显示错误

重要:切勿静默吞没错误。

// 正确 - 错误始终向用户展示
const [createItem, { loading }] = useCreateItemMutation({
  onCompleted: () => {
    toast.success({ title: '项目已创建' });
  },
  onError: (error) => {
    console.error('createItem 失败:', error);
    toast.error({ title: '创建项目失败' });
  },
});

// 错误 - 错误被静默捕获,用户无感知
const [createItem] = useCreateItemMutation({
  onError: (error) => {
    console.error(error); // 用户什么都看不到!
  },
});

错误状态组件模式

interface ErrorStateProps {
  error: Error;
  onRetry?: () => void;
  title?: string;
}

const ErrorState = ({ error, onRetry, title }: ErrorStateProps) => (
  <div className="error-state">
    <Icon name="exclamation-circle" />
    <h3>{title ?? '出了点问题'}</h3>
    <p>{error.message}</p>
    {onRetry && (
      <Button onClick={onRetry}>重试</Button>
    )}
  </div>
);

按钮状态模式

按钮加载状态

<Button
  onClick={handleSubmit}
  isLoading={isSubmitting}
  disabled={!isValid || isSubmitting}
>
  提交
</Button>

操作期间禁用

重要:在异步操作期间务必禁用触发元素。

// 正确 - 加载时按钮禁用
<Button
  disabled={isSubmitting}
  isLoading={isSubmitting}
  onClick={handleSubmit}
>
  提交
</Button>

// 错误 - 用户可以多次点击
<Button onClick={handleSubmit}>
  {isSubmitting ? '提交中...' : '提交'}
</Button>

空状态

空状态要求

每个列表/集合必须具有空状态:

// 错误 - 没有空状态
return <FlatList data={items} />;

// 正确 - 显式空状态
return (
  <FlatList
    data={items}
    ListEmptyComponent={<EmptyState />}
  />
);

上下文相关的空状态

// 搜索无结果
<EmptyState
  icon="search"
  title="未找到结果"
  description="尝试不同的搜索词"
/>

// 列表尚无项目
<EmptyState
  icon="plus-circle"
  title="暂无项目"
  description="创建您的第一个项目"
  action={{ label: '创建项目', onClick: handleCreate }}
/>

表单提交流程

const MyForm = () => {
  const [submit, { loading }] = useSubmitMutation({
    onCompleted: handleSuccess,
    onError: handleError,
  });

  const handleSubmit = async () => {
    if (!isValid) {
      toast.error({ title: '请修正错误' });
      return;
    }
    await submit({ variables: { input: values } });
  };

  return (
    <form>
      <Input
        value={values.name}
        onChange={handleChange('name')}
        error={touched.name ? errors.name : undefined}
      />
      <Button
        type="submit"
        onClick={handleSubmit}
        disabled={!isValid || loading}
        isLoading={loading}
      >
        提交
      </Button>
    </form>
  );
};

反模式

加载状态

// 错误 - 数据存在时显示旋转器(导致闪烁)
if (loading) return <Spinner />;

// 正确 - 仅在没有数据时显示加载
if (loading && !data) return <Spinner />;

错误处理

// 错误 - 错误被吞没
try {
  await mutation();
} catch (e) {
  console.log(e); // 用户毫不知情!
}

// 正确 - 错误被暴露
onError: (error) => {
  console.error('操作失败:', error);
  toast.error({ title: '操作失败' });
}

按钮状态

// 错误 - 提交时未禁用按钮
<Button onClick={submit}>提交</Button>

// 正确 - 禁用并显示加载状态
<Button onClick={submit} disabled={loading} isLoading={loading}>
  提交
</Button>

检查清单

在完成任何 UI 组件之前:

UI 状态:

  • 错误状态已处理并向用户展示
  • 仅在没有数据时显示加载状态
  • 集合提供了空状态
  • 异步操作期间按钮已禁用
  • 按钮在适当时候显示加载指示器

数据与变更:

  • 变更操作有 onError 处理程序
  • 所有用户操作都有反馈(toast/视觉)

与其他技能的集成

  • graphql-schema:使用带有正确错误处理的变更模式
  • testing-patterns:测试所有 UI 状态(加载、错误、空、成功)
  • formik-patterns:应用表单提交模式

Individual skills in this repo

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

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相关技能