react-server-components-framework
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseReact Server Components Framework
React Server Components 框架
Overview
概述
React Server Components (RSC) enable server-first rendering with client-side interactivity. This skill covers Next.js 16 App Router patterns, Server Components, Server Actions, and streaming.
When to use this skill:
- Building Next.js 16+ applications with the App Router
- Designing component boundaries (Server vs Client Components)
- Implementing data fetching with caching and revalidation
- Creating mutations with Server Actions
- Optimizing performance with streaming and Suspense
React Server Components (RSC) 支持服务端优先渲染并兼顾客户端交互。本技能涵盖Next.js 16 App Router模式、Server Components、Server Actions以及流式渲染。
适用场景:
- 基于App Router构建Next.js 16+应用
- 设计组件边界(服务端组件 vs 客户端组件)
- 实现带缓存和重新验证的数据获取
- 用Server Actions创建变更操作
- 通过流式渲染和Suspense优化性能
Quick Reference
速查指南
Server vs Client Components
服务端组件 vs 客户端组件
| Feature | Server Component | Client Component |
|---|---|---|
| Directive | None (default) | |
| Async/await | Yes | No |
| Hooks | No | Yes |
| Browser APIs | No | Yes |
| Database access | Yes | No |
| Client JS bundle | Zero | Ships to client |
Key Rule: Server Components can render Client Components, but Client Components cannot directly import Server Components (use prop instead).
children| 特性 | 服务端组件 | 客户端组件 |
|---|---|---|
| 指令 | 无(默认) | |
| 异步等待 | 支持 | 不支持 |
| 钩子函数 | 不支持 | 支持 |
| 浏览器API | 不支持 | 支持 |
| 数据库访问 | 支持 | 不支持 |
| 客户端JS包 | 零体积 | 会打包发送到客户端 |
核心规则:服务端组件可以渲染客户端组件,但客户端组件不能直接导入服务端组件(改用属性)。
childrenData Fetching Quick Reference
数据获取速查
Next.js 16 Cache Components (Recommended):
tsx
import { cacheLife, cacheTag } from 'next/cache'
// Cached component with duration
async function CachedProducts() {
'use cache'
cacheLife('hours')
cacheTag('products')
return await db.product.findMany()
}
// Invalidate cache
import { revalidateTag } from 'next/cache'
revalidateTag('products')Legacy Fetch Options (Next.js 15):
tsx
// Static (cached indefinitely)
await fetch(url, { cache: 'force-cache' })
// Revalidate every 60 seconds
await fetch(url, { next: { revalidate: 60 } })
// Always fresh
await fetch(url, { cache: 'no-store' })
// Tag-based revalidation
await fetch(url, { next: { tags: ['posts'] } })Next.js 16 Cache Components(推荐):
tsx
import { cacheLife, cacheTag } from 'next/cache'
// 带缓存时长的组件
async function CachedProducts() {
'use cache'
cacheLife('hours')
cacheTag('products')
return await db.product.findMany()
}
// 失效缓存
import { revalidateTag } from 'next/cache'
revalidateTag('products')Next.js 15 传统Fetch选项:
tsx
// 静态缓存(永久缓存)
await fetch(url, { cache: 'force-cache' })
// 每60秒重新验证一次
await fetch(url, { next: { revalidate: 60 } })
// 始终获取最新数据
await fetch(url, { cache: 'no-store' })
// 基于标签的重新验证
await fetch(url, { next: { tags: ['posts'] } })Server Actions Quick Reference
Server Actions 速查
tsx
'use server'
export async function createPost(formData: FormData) {
const title = formData.get('title') as string
const post = await db.post.create({ data: { title } })
revalidatePath('/posts')
redirect("/posts/" + post.id)
}tsx
'use server'
export async function createPost(formData: FormData) {
const title = formData.get('title') as string
const post = await db.post.create({ data: { title } })
revalidatePath('/posts')
redirect("/posts/" + post.id)
}Async Params/SearchParams (Next.js 16)
异步参数/搜索参数(Next.js 16)
Route parameters and search parameters are now Promises that must be awaited:
tsx
// app/posts/[slug]/page.tsx
export default async function PostPage({
params,
searchParams,
}: {
params: Promise<{ slug: string }>
searchParams: Promise<{ page?: string }>
}) {
const { slug } = await params
const { page } = await searchParams
return <Post slug={slug} page={page} />
}Note: Also applies to , , and route handlers. See for complete migration guide.
layout.tsxgenerateMetadata()references/nextjs-16-upgrade.md路由参数和搜索参数现在是需要等待的Promise:
tsx
// app/posts/[slug]/page.tsx
export default async function PostPage({
params,
searchParams,
}: {
params: Promise<{ slug: string }>
searchParams: Promise<{ page?: string }>
}) {
const { slug } = await params
const { page } = await searchParams
return <Post slug={slug} page={page} />
}注意:此规则同样适用于、和路由处理器。完整迁移指南请参考。
layout.tsxgenerateMetadata()references/nextjs-16-upgrade.mdReferences
参考文档
Server Components
服务端组件
See:
references/server-components.mdKey topics covered:
- Async server components and direct database access
- Data fetching patterns (parallel, sequential, cached)
- Route segment config (dynamic, revalidate, PPR)
- generateStaticParams for SSG
- Error handling and composition patterns
参考:
references/server-components.md涵盖核心主题:
- 异步服务端组件与直接数据库访问
- 数据获取模式(并行、串行、缓存)
- 路由段配置(动态、重新验证、PPR)
- 用于SSG的generateStaticParams
- 错误处理与组合模式
Client Components
客户端组件
See:
references/client-components.mdKey topics covered:
- The directive and boundary rules
'use client' - React 19 patterns (function declarations, ref as prop)
- Interactivity patterns (state, forms, events)
- Hydration and avoiding hydration mismatches
- Composition with Server Components via children
参考:
references/client-components.md涵盖核心主题:
- 指令与边界规则
'use client' - React 19模式(函数声明、Ref作为属性)
- 交互模式(状态、表单、事件)
- hydration与避免 hydration 不匹配
- 通过children属性与服务端组件组合
Streaming Patterns
流式渲染模式
See:
references/streaming-patterns.mdKey topics covered:
- Suspense boundaries and loading states
- loading.tsx automatic wrapping
- Parallel streaming and nested Suspense
- Partial Prerendering (PPR)
- Skeleton component best practices
参考:
references/streaming-patterns.md涵盖核心主题:
- Suspense边界与加载状态
- loading.tsx自动包裹
- 并行流式渲染与嵌套Suspense
- 部分预渲染(PPR)
- 骨架组件最佳实践
React 19 Patterns
React 19模式
See:
references/react-19-patterns.mdKey topics covered:
- Function declarations over React.FC
- Ref as prop (forwardRef removal)
- useActionState, useFormStatus, useOptimistic
- Activity component for preloading UI
- useEffectEvent hook
参考:
references/react-19-patterns.md涵盖核心主题:
- 优先使用函数声明而非React.FC
- Ref作为属性(移除forwardRef)
- useActionState、useFormStatus、useOptimistic
- 用于预加载UI的Activity组件
- useEffectEvent钩子
Server Actions
Server Actions
See:
references/server-actions.mdKey topics covered:
- Progressive enhancement patterns
- Form handling with useActionState
- Validation with Zod
- Optimistic updates
参考:
references/server-actions.md涵盖核心主题:
- 渐进增强模式
- 结合useActionState处理表单
- 用Zod做验证
- 乐观更新
Routing Patterns
路由模式
See:
references/routing-patterns.mdKey topics covered:
- Parallel routes for simultaneous rendering
- Intercepting routes for modals
- Route groups for organization
- Dynamic and catch-all routes
参考:
references/routing-patterns.md涵盖核心主题:
- 并行路由实现同时渲染
- 拦截路由实现模态框
- 路由组用于组织代码
- 动态路由与兜底路由
Migration Guide
迁移指南
See:
references/migration-guide.mdKey topics covered:
- Pages Router to App Router migration
- getServerSideProps/getStaticProps replacement
- Layout and metadata migration
参考:
references/migration-guide.md涵盖核心主题:
- Pages Router到App Router的迁移
- getServerSideProps/getStaticProps的替代方案
- 布局与元数据迁移
Cache Components (Next.js 16)
Cache Components(Next.js 16)
See:
references/cache-components.mdImportant: Cache Components replaces as the declarative caching model in Next.js 16.
experimental_pprKey topics covered:
- The directive replacing
"use cache"experimental_ppr - for fine-grained cache duration control
cacheLife() - and
cacheTag()for on-demand invalidationrevalidateTag() - Configuration: in next.config.ts
cacheComponents: true - Before/after migration examples (Next.js 15 to 16)
- Integration with Partial Prerendering (PPR)
- Serialization rules and constraints
参考:
references/cache-components.md重要提示:Cache Components替代了,成为Next.js 16中的声明式缓存模型。
experimental_ppr涵盖核心主题:
- 替代的
experimental_ppr指令"use cache" - 用于细粒度缓存时长控制的
cacheLife() - 用于按需失效的和
cacheTag()revalidateTag() - 配置:在next.config.ts中设置
cacheComponents: true - Next.js 15到16的迁移示例
- 与部分预渲染(PPR)的集成
- 序列化规则与约束
Next.js 16 Upgrade Guide
Next.js 16升级指南
See:
references/nextjs-16-upgrade.mdKey topics covered:
- Version requirements (Node.js 20.9+, TypeScript 5.1+)
- Breaking changes (async params, cookies, headers)
- middleware.ts to proxy.ts migration
- PPR removal and Cache Components replacement
- Turbopack as default bundler
- New caching APIs (updateTag, refresh, revalidateTag)
参考:
references/nextjs-16-upgrade.md涵盖核心主题:
- 版本要求(Node.js 20.9+、TypeScript 5.1+)
- 破坏性变更(异步参数、Cookies、Headers)
- middleware.ts到proxy.ts的迁移
- PPR移除与Cache Components替代
- Turbopack作为默认打包工具
- 新缓存API(updateTag、refresh、revalidateTag)
TanStack Router
TanStack Router
See:
references/tanstack-router-patterns.mdKey topics covered:
- React 19 features without Next.js
- Route-based data fetching
- Client-rendered app patterns
参考:
references/tanstack-router-patterns.md涵盖核心主题:
- 不依赖Next.js使用React 19特性
- 基于路由的数据获取
- 客户端渲染应用模式
Searching References
参考文档搜索
bash
undefinedbash
undefinedFind component patterns
查找组件模式
grep -r "Server Component" references/
grep -r "Server Component" references/
Search for data fetching strategies
搜索数据获取策略
grep -A 10 "Caching Strategies" references/data-fetching.md
grep -A 10 "Caching Strategies" references/data-fetching.md
Find Server Actions examples
查找Server Actions示例
grep -B 5 "Progressive Enhancement" references/server-actions.md
grep -B 5 "Progressive Enhancement" references/server-actions.md
Locate routing patterns
定位路由模式
grep -n "Parallel Routes" references/routing-patterns.md
---grep -n "Parallel Routes" references/routing-patterns.md
---Best Practices Summary
最佳实践总结
Component Boundaries
组件边界
- Keep Client Components at the edges (leaves) of the component tree
- Use Server Components by default
- Extract minimal interactive parts to Client Components
- Pass Server Components as to Client Components
children
- 将客户端组件放在组件树的边缘(叶子节点)
- 默认使用服务端组件
- 仅将最小交互部分提取为客户端组件
- 通过children属性将服务端组件传递给客户端组件
Data Fetching
数据获取
- Fetch data in Server Components close to where it's used
- Use parallel fetching () for independent data
Promise.all - Set appropriate cache and revalidate options
- Use for static routes
generateStaticParams
- 在靠近使用位置的服务端组件中获取数据
- 对独立数据使用并行获取()
Promise.all - 设置合适的缓存和重新验证选项
- 对静态路由使用
generateStaticParams
Performance
性能优化
- Use Suspense boundaries for streaming
- Implement loading.tsx for instant loading states
- Enable PPR for static/dynamic mix
- Use route segment config to control rendering mode
- 使用Suspense边界实现流式渲染
- 实现loading.tsx提供即时加载状态
- 启用PPR实现静态/动态混合
- 用路由段配置控制渲染模式
Templates
模板
- - Basic async Server Component with data fetching
scripts/ServerComponent.tsx - - Interactive Client Component with hooks
scripts/ClientComponent.tsx - - Server Action with validation and revalidation
scripts/ServerAction.tsx
- - 带数据获取的基础异步服务端组件
scripts/ServerComponent.tsx - - 带钩子函数的交互式客户端组件
scripts/ClientComponent.tsx - - 带验证和重新验证的Server Action
scripts/ServerAction.tsx
Troubleshooting
故障排查
| Error | Fix |
|---|---|
| "You're importing a component that needs useState" | Add |
| "async/await is not valid in non-async Server Components" | Add |
| "Cannot use Server Component inside Client Component" | Pass Server Component as |
| "Hydration mismatch" | Use |
| "params is not defined" or params returning Promise | Add |
| "experimental_ppr is not a valid export" | Use Cache Components with |
| "cookies/headers is not a function" | Add |
| 错误 | 解决方法 |
|---|---|
| "You're importing a component that needs useState" | 添加 |
| "async/await is not valid in non-async Server Components" | 为函数声明添加 |
| "Cannot use Server Component inside Client Component" | 将服务端组件作为 |
| "Hydration mismatch" | 对Date.now()、Math.random()、浏览器API使用 |
| "params is not defined" 或 params返回Promise | 在 |
| "experimental_ppr is not a valid export" | 改用带 |
| "cookies/headers is not a function" | 在 |
Resources
资源
Related Skills
相关技能
After mastering React Server Components:
- Streaming API Patterns - Real-time data patterns
- Type Safety & Validation - tRPC integration
- Edge Computing Patterns - Global deployment
- Performance Optimization - Core Web Vitals
掌握React Server Components后可继续学习:
- 流式API模式 - 实时数据模式
- 类型安全与验证 - tRPC集成
- 边缘计算模式 - 全球部署
- 性能优化 - 核心Web指标
Capability Details
能力细节
react-19-patterns
react-19-patterns
Keywords: react 19, React.FC, forwardRef, useActionState, useFormStatus, useOptimistic, function declaration
Solves:
- How do I replace React.FC in React 19?
- forwardRef replacement pattern
- useActionState vs useFormState
- React 19 component declaration best practices
关键词:react 19、React.FC、forwardRef、useActionState、useFormStatus、useOptimistic、函数声明
解决问题:
- 如何在React 19中替代React.FC?
- forwardRef替代模式
- useActionState与useFormState的区别
- React 19组件声明最佳实践
use-hook-suspense
use-hook-suspense
Keywords: use(), use hook, suspense, promise, data fetching, promise cache, cachePromise
Solves:
- How do I use the use() hook in React 19?
- Suspense-native data fetching pattern
- Promise caching to prevent infinite loops
关键词:use()、use钩子、suspense、promise、数据获取、promise缓存、cachePromise
解决问题:
- 如何在React 19中使用use()钩子?
- 基于Suspense的数据获取模式
- Promise缓存避免无限循环
optimistic-updates-async
optimistic-updates-async
Keywords: useOptimistic, useTransition, optimistic update, instant ui, auto rollback
Solves:
- How to show instant UI updates before API responds?
- useOptimistic with useTransition pattern
- Auto-rollback on API failure
关键词:useOptimistic、useTransition、乐观更新、即时UI、自动回滚
解决问题:
- 如何在API响应前显示即时UI更新?
- useOptimistic结合useTransition模式
- API失败时自动回滚
rsc-patterns
rsc-patterns
Keywords: rsc, server component, client component, use client, use server
Solves:
- When to use server vs client components?
- RSC boundaries and patterns
关键词:rsc、server component、client component、use client、use server
解决问题:
- 何时使用服务端组件 vs 客户端组件?
- RSC边界与模式
server-actions
server-actions
Keywords: server action, form action, use server, mutation
Solves:
- How do I create a server action?
- Form handling with server actions
关键词:server action、form action、use server、mutation
解决问题:
- 如何创建Server Action?
- 用Server Actions处理表单
data-fetching
data-fetching
Keywords: fetch, data fetching, async component, loading, suspense
Solves:
- How do I fetch data in RSC?
- Async server components
关键词:fetch、数据获取、异步组件、加载、suspense
解决问题:
- 如何在RSC中获取数据?
- 异步服务端组件
streaming-ssr
streaming-ssr
Keywords: streaming, ssr, suspense boundary, loading ui
Solves:
- How do I stream server content?
- Progressive loading patterns
关键词:streaming、ssr、suspense boundary、加载UI
解决问题:
- 如何流式传输服务端内容?
- 渐进式加载模式
caching
caching
Keywords: cache, revalidate, static, dynamic, isr
Solves:
- How do I cache in Next.js 16?
- Revalidation strategies
关键词:cache、revalidate、static、dynamic、isr
解决问题:
- 如何在Next.js 16中实现缓存?
- 重新验证策略
cache-components
cache-components
Keywords: use cache, cacheLife, cacheTag, cacheComponents, revalidateTag, updateTag, cache directive
Solves:
- How do I use the "use cache" directive?
- What replaced experimental_ppr?
- How do I set cache duration with cacheLife?
- How do I invalidate cache with cacheTag?
- How do I migrate from Next.js 15 fetch caching to use cache?
关键词:use cache、cacheLife、cacheTag、cacheComponents、revalidateTag、updateTag、cache directive
解决问题:
- 如何使用"use cache"指令?
- 什么替代了experimental_ppr?
- 如何用cacheLife设置缓存时长?
- 如何用cacheTag失效缓存?
- 如何从Next.js 15的Fetch缓存迁移到use cache?
tanstack-router-patterns
tanstack-router-patterns
Keywords: tanstack router, react router, vite, spa, client rendering, prefetch
Solves:
- How do I use React 19 features without Next.js?
- TanStack Router prefetching setup
- Route-based data fetching with TanStack Query
关键词:tanstack router、react router、vite、spa、客户端渲染、预获取
解决问题:
- 如何不依赖Next.js使用React 19特性?
- TanStack Router预获取配置
- 结合TanStack Query实现基于路由的数据获取
async-params
async-params
Keywords: async params, searchParams, Promise params, await params, dynamic route params
Solves:
- How do I access params in Next.js 16?
- Why are my route params undefined?
- How do I use searchParams in Next.js 16?
- How do I type params as Promise?
关键词:async params、searchParams、Promise params、await params、动态路由参数
解决问题:
- 如何在Next.js 16中访问参数?
- 为什么我的路由参数未定义?
- 如何在Next.js 16中使用searchParams?
- 如何将参数类型声明为Promise?
nextjs-16-upgrade
nextjs-16-upgrade
Keywords: next.js 16, nextjs 16, upgrade, migration, breaking changes, async params, turbopack, proxy.ts, cache components
Solves:
- How do I upgrade to Next.js 16?
- What are the breaking changes in Next.js 16?
- How do I migrate middleware.ts to proxy.ts?
- How do I use async params and searchParams?
- What replaced experimental_ppr?
- How do I use the new caching APIs?
关键词:next.js 16、nextjs 16、升级、迁移、破坏性变更、async params、turbopack、proxy.ts、cache components
解决问题:
- 如何升级到Next.js 16?
- Next.js 16有哪些破坏性变更?
- 如何将middleware.ts迁移到proxy.ts?
- 如何使用异步参数和searchParams?
- 什么替代了experimental_ppr?
- 如何使用新的缓存API?