title: Server Components 深入
Server Components 深入
React Server Components (RSC) 是 Next.js 16 的核心特性之一。
什么是 Server Components?
Server Components 在服务器上渲染,永远不会发送到客户端:
// app/posts/page.tsx
async function Posts() {
// 直接访问数据库
const posts = await db.query('SELECT * FROM posts')
return (
<div>
{posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</article>
))}
</div>
)
}
优势
- 零客户端 JavaScript:Server Components 的代码不会发送到浏览器
- 直接访问后端资源:数据库、文件系统、密钥等
- 自动代码分割:只发送必要的客户端代码
- 更好的 SEO:完全渲染的 HTML
数据获取
在 Server Components 中可以直接使用 async/await:
async function UserProfile({ userId }: { userId: string }) {
const user = await fetch(`https://api.example.com/users/${userId}`)
.then(r => r.json())
return (
<div>
<h1>{user.name}</h1>
<p>{user.bio}</p>
</div>
)
}
缓存策略
Next.js 16 提供了强大的缓存功能:
// 默认缓存
const data = await fetch('https://api.example.com/data')
// 不缓存
const data = await fetch('https://api.example.com/data', {
cache: 'no-store'
})
// 60秒后重新验证
const data = await fetch('https://api.example.com/data', {
next: { revalidate: 60 }
})
使用 "use cache"
Next.js 16 引入了新的 "use cache" 指令来缓存组件或函数:
'use cache'
async function CachedData() {
const data = await expensiveOperation()
return <div>{data}</div>
}
限制
Server Components 不能使用:
- React Hooks(useState、useEffect 等)
- 浏览器 API
- 事件处理器
需要这些功能时,使用 Client Components。
小结
Server Components 改变了我们构建 React 应用的方式,合理使用可以显著提升性能!