← 返回首页

react-nextjs-best-practices@1.0.0

React 19 和 Next.js 15 最佳实践与编码规范

CLI 安装指南

通过 SkillSPAI CLI 一键安装到你的 AI 编码工具:

1. 安装 CLI(如尚未安装)

npm install -g skillspai

2. 安装此 Skill 到目标平台

# Codex CLI
skillspai install react-nextjs-best-practices --target codex

# Claude Code
skillspai install react-nextjs-best-practices --target claude

# Cursor
skillspai install react-nextjs-best-practices --target cursor

# Windsurf
skillspai install react-nextjs-best-practices --target windsurf

# OpenCode
skillspai install react-nextjs-best-practices --target opencode

3. 或指定版本安装

skillspai install react-nextjs-best-practices@1.0.0 --target claude

Skill 内容

# React 19 + Next.js 15 最佳实践

## 核心原则

- 优先使用 Server Components,只在需要交互时用 `"use client"`
- 使用 `async/await` 处理 Next.js 15 的异步 `params` 和 `searchParams`
- 避免在 Server Components 中使用 `useState`、`useEffect`、事件处理器

## 组件规范

- 一个文件一个组件,文件名与组件名一致
- Props 用 TypeScript interface 定义,不用 type
- 组件不超过 150 行,超过则拆分
- 使用 `React.memo()` 优化频繁重渲染的列表项

## 数据获取

- Server Components 中直接 `await` 数据请求,不要用 `useEffect`
- 使用 `fetch` 的 `next: { revalidate }` 选项做 ISR
- 表单用 Server Actions(`"use server"`),不要写 API 路由处理简单 CRUD
- 错误处理用 `error.tsx` 边界,不要 try-catch 包裹整个组件

## 路由和导航

- 使用 `Link` 组件做客户端导航,不要用 `<a>` 标签做站内链接
- 动态路由用 `[param]` 命名,文件夹结构即路由
- 中间件 `middleware.ts` 做认证和重定向,不要在页面里检查

## 样式

- 优先 Tailwind CSS,避免写自定义 CSS
- 使用 `cn()` 工具函数合并类名(clsx + tailwind-merge)
- 响应式用 Tailwind 断点(sm/md/lg/xl),不要写媒体查询

## 性能

- 图片用 `next/image`,自动优化和懒加载
- 字体用 `next/font`,避免 FOUT
- 大组件用 `dynamic()` 做代码分割
- 列表渲染必须提供稳定的 `key`,不要用 index

## 常见错误

- 不要在 Server Component 中导入客户端组件的事件处理器
- 不要在 layout.tsx 中使用 `useSearchParams`(会导致整页 CSR)
- 不要忘记 `await cookies()` / `await headers()`(Next.js 15 是异步的)
- 不要在 Server Action 中使用 `redirect()` 后继续执行代码