# 服务端组件与服务端 Actions
React 19 服务端组件在服务器上运行,可以是异步的,并支持零包大小的数据获取。服务端 Actions 通过渐进式增强处理数据变更。
## 异步服务端组件
服务端组件可以是异步函数 — 直接 await 数据获取。
typescript
// app/users/[id]/page.tsx
type PageProps = {
params: { id: string };
searchParams?: { tab?: string; edit?: string };
};
export default async function UserPage({ params, searchParams }: PageProps) {
// 在服务器上运行 - 无客户端包
const user = await fetchUser(params.id);
const posts = await fetchUserPosts(params.id);
return (
{searchParams?.edit === 'true' && (
)}
);
}
async function fetchUser(id: string): Promise {
const res = await fetch(`https://api.example.com/users/${id}`, {
cache: 'no-store', // 或 'force-cache', 'revalidate'
});
if (!res.ok) throw new Error('Failed to fetch user');
return res.json();
}
## 并行数据获取
使用 Promise.all 并行获取多个资源。
typescript
type DashboardProps = {
params: { userId: string };
};
export default async function Dashboard({ params }: DashboardProps) {
// 并行获取
const [user, stats, activity] = await Promise.all([
fetchUser(params.userId),
fetchUserStats(params.userId),
fetchRecentActivity(params.userId),
]);
return (
);
}
## 顺序获取 vs 瀑布式获取
typescript
// ❌ 瀑布式 - 慢
async function SlowPage() {
const user = await fetchUser('123');
const posts = await fetchUserPosts(user.id); // 等待 user
const comments = await fetchPostComments(posts[0].id); // 等待 posts
return
...
;
}
// ✅ 并行 - 快
async function FastPage() {
const userPromise = fetchUser('123');
const postsPromise = fetchUserPosts('123');
const [user, posts] = await Promise.all([userPromise, postsPromise]);
// 如果评论依赖于 posts,则在之后获取
const comments = await fetchPostComments(posts[0].id);
return
...
;
}
## 服务端 Actions - 表单变更
标记为 'use server' 的服务端 Actions