React Server Components(RSC)是 React 架构的重大革新,在服务端渲染组件,减少客户端 JavaScript。
核心概念
Server Components vs Client Components
| 特性 | Server Components | Client Components |
|---|---|---|
| 渲染位置 | 服务器 | 浏览器 |
| JS Bundle | 不打包到客户端 | 打包到客户端 |
| 直接访问后端 | 可以 | 不可以 |
| 使用 useState | 不可以 | 可以 |
| 使用 useEffect | 不可以 | 可以 |
Server Component
tsx
// app/articles/page.tsx (Server Component)
import { db } from '@/lib/database';
// 直接访问数据库,无需 API
export default async function ArticlesPage() {
const articles = await db.article.findMany({
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 20,
});
return (
<div>
<h1>最新文章</h1>
{articles.map((article) => (
<ArticleCard key={article.id} article={article} />
))}
</div>
);
}Client Component
tsx
'use client';
import { useState } from 'react';
export function LikeButton({ articleId }: { articleId: number }) {
const [liked, setLiked] = useState(false);
const [count, setCount] = useState(0);
const handleClick = async () => {
setLiked(!liked);
setCount((prev) => prev + (liked ? -1 : 1));
await fetch(`/api/articles/${articleId}/like`, { method: 'POST' });
};
return (
<button>
{liked ? '❤️' : '🤍'} {count}
</button>
);
}组合使用
tsx
// Server Component 中可以嵌套 Client Component
import { db } from '@/lib/database';
import { LikeButton } from './LikeButton';
export default async function ArticleDetail({ id }: { id: number }) {
const article = await db.article.findUnique({ where: { id } });
return (
<article>
<h1>{article.title}</h1>
<div>{article.content}</div>
{/* Client Component 可以接收 Server Component 传递的 props */}
<LikeButton articleId={article.id} />
</article>
);
}数据获取与缓存
tsx
// 使用 fetch 的缓存控制
export default async function Page() {
const res = await fetch('https://api.example.com/data', {
next: { revalidate: 3600 }, // 每小时重新验证
});
const data = await res.json();
return <Dashboard data={data} />;
}
// 使用 unstable_noStore 禁用缓存
import { unstable_noStore as noStore } from 'next/cache';
export default async function RealtimePage() {
noStore();
const data = await fetch('https://api.example.com/realtime');
return <RealtimeData data={await data.json()} />;
}Streaming 与 Suspense
tsx
import { Suspense } from 'react';
export default function Page() {
return (
<div>
<h1>仪表盘</h1>
{/* 立即显示 */}
<StatsOverview />
{/* 流式加载:先显示 fallback,数据就绪后替换 */}
<Suspense fallback={<ChartSkeleton />}>
<SlowChart />
</Suspense>
<Suspense fallback={<div>加载评论...</div>}>
<Comments />
</Suspense>
</div>
);
}Server Actions
tsx
'use server';
import { revalidatePath } from 'next/cache';
import { db } from '@/lib/database';
export async function createArticle(formData: FormData) {
const title = formData.get('title') as string;
const content = formData.get('content') as string;
await db.article.create({
data: { title, content, authorId: 1 },
});
revalidatePath('/articles');
}总结
React Server Components 将渲染逻辑移到服务端,减少了客户端 JavaScript 体积,提升了首屏加载速度。Server Components 可以直接访问数据库,Client Components 处理交互。两者通过 props 传递数据,结合 Suspense 实现流式渲染。



请登录后发表评论
登录 注册
-
最新
-
最热
只看作者