React Server Components 深度解析
React Server Components 深度解析 ⚡
React Server Components 是 React 18 引入的一个革命性功能,它改变了我们构建 React 应用的方式。
🤔 什么是 Server Components?
Server Components 是在服务器上渲染的 React 组件,它们可以:
🆚 Server Components vs Client Components
Server Components
Client Components
🚀 在 Next.js 中使用
1. Server Component 示例
tsx// app/posts/page.tsx (Server Component)
async function getPosts() {
const res = await fetch('https://api.example.com/posts');
return res.json();
}
export default async function PostsPage() {
const posts = await getPosts();
return (
<div>
<h1>博客文章</h1>
{posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.excerpt}</p>
</article>
))}
</div>
);
}
2. Client Component 示例
tsx// components/LikeButton.tsx (Client Component)
'use client';
import { useState } from 'react';
export default function LikeButton() {
const [liked, setLiked] = useState(false);
return (
<button
onClick={() => setLiked(!liked)}
className={liked ? 'text-red-500' : 'text-gray-500'}
>
{liked ? '❤️' : '🤍'} 点赞
</button>
);
}
🏗️ 组合模式
1. Server Component 中使用 Client Component
tsx// app/post/[id]/page.tsx (Server Component)
import LikeButton from '@/components/LikeButton';
async function getPost(id: string) {
// 服务器端数据获取
}
export default async function PostPage({ params }) {
const post = await getPost(params.id);
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
<LikeButton /> {/* Client Component */}
</article>
);
}
2. 通过 props 传递数据
tsx// Server Component
export default async function BlogPage() {
const posts = await getPosts();
return (
<div>
<PostList posts={posts} /> {/* 传递数据给 Client Component */}
</div>
);
}
// Client Component
'use client';
export default function PostList({ posts }) {
const [filter, setFilter] = useState('');
const filteredPosts = posts.filter(post =>
post.title.includes(filter)
);
return (
<div>
<input
value={filter}
onChange={(e) => setFilter(e.target.value)}
placeholder="搜索文章..."
/>
{filteredPosts.map(post => (
<PostCard key={post.id} post={post} />
))}
</div>
);
}
🎯 最佳实践
1. 数据获取
tsxasync function BlogPage() {
// 并行获取数据
const [posts, categories] = await Promise.all([
getPosts(),
getCategories()
]);
return (
<div>
<Categories categories={categories} />
<Posts posts={posts} />
</div>
);
}
2. 错误处理
tsx// app/posts/error.tsx
'use client';
export default function Error({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
return (
<div>
<h2>出错了!</h2>
<p>{error.message}</p>
<button onClick={reset}>重试</button>
</div>
);
}
3. 加载状态
tsx// app/posts/loading.tsx
export default function Loading() {
return (
<div className="animate-pulse">
<div className="h-8 bg-gray-200 rounded mb-4"></div>
<div className="space-y-4">
{[1, 2, 3].map(i => (
<div key={i} className="h-24 bg-gray-200 rounded"></div>
))}
</div>
</div>
);
}
🔧 调试技巧
1. 组件边界
2. 性能监控
🌟 总结
React Server Components 为我们提供了:
Server Components 是 React 和 Next.js 的未来,掌握它们将让你的应用更加高效和现代化! 🚀