React Server Components 详解
React Server Components (RSC) 是 React 团队推出的一项革命性技术,它允许开发者创建在服务器上渲染且不需要 JavaScript 包的 React 组件。本文将详细介绍 RSC 的工作原理、核心优势,以及如何在项目中有效地使用它们。
什么是 React Server Components
React Server Components 是在服务器上渲染的特殊 React 组件,它们可以:
- 直接访问服务器资源(如数据库、文件系统等)
- 将渲染结果(而非代码)发送到客户端
- 减少客户端 JavaScript 包的大小
- 与客户端组件无缝交互
Server Components vs. Client Components
特性 | Server Components | Client Components |
---|---|---|
渲染位置 | 服务器 | 客户端 |
可访问服务器资源 | ✅ | ❌ |
可使用浏览器 API | ❌ | ✅ |
可使用 React hooks | ❌ | ✅ |
可处理用户交互 | ❌ | ✅ |
包含在 JS 包中 | ❌ | ✅ |
如何使用 Server Components
在 Next.js 13+的 App Router 中,所有组件默认都是 Server Components。如果需要使用客户端特性,可以在文件顶部添加"use client"
指令,将其标记为 Client Component。
Server Component 示例
// 这是一个Server Component
import { db } from '@/lib/db'
async function UserProfile({ userId }) {
// 直接从数据库获取数据,无需API
const user = await db.user.findUnique({
where: { id: userId }
})
return (
<div>
<h1>{user.name}</h1>
<p>{user.bio}</p>
</div>
)
}
Client Component 示例
'use client'
// 这是一个Client Component
import { useState } from 'react'
export default function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
)
}
数据获取模式
Server Components 彻底改变了 React 应用的数据获取方式:
// 旧方式 (在客户端获取)
function Profile() {
const [user, setUser] = useState(null)
useEffect(() => {
fetch('/api/user')
.then((res) => res.json())
.then((data) => setUser(data))
}, [])
if (!user) return <p>Loading...</p>
return <h1>{user.name}</h1>
}
// 新方式 (在服务器获取)
async function Profile() {
const user = await db.user.findUnique({
where: { id: 'current-user' }
})
return <h1>{user.name}</h1>
}
组合 Server 和 Client 组件
Server 组件可以导入和渲染 Client 组件,但反过来不行:
// ServerComponent.jsx
import ClientComponent from './ClientComponent';
export default function ServerComponent() {
return (
<div>
<h1>Server Component</h1>
<ClientComponent /> {/* 有效 */}
</div>
);
}
// ClientComponent.jsx
"use client"
import ServerComponent from './ServerComponent';
export default function ClientComponent() {
return (
<div>
<h1>Client Component</h1>
{/* ❌ 不能直接渲染Server组件 */}
{/* <ServerComponent /> */}
</div>
);
}
性能优势
使用 React Server Components 有显著的性能优势:
- 减少 JavaScript 包大小:服务器组件代码不会被发送到客户端
- 更快的首次加载:无需等待 JavaScript 下载和执行
- 直接数据访问:无需额外的 API 层
- 渐进式增强:React 可以交互式地流式传输 UI,使用户能够更快地看到页面
最佳实践
- 尽可能使用 Server Components,除非需要客户端特定功能
- 将 Client Components 移至树的叶子节点,以最小化客户端 JavaScript
- 使用”提升状态”模式,保持 Client Components 尽可能小
- 在 Server Components 中进行数据获取,然后将数据作为 props 传递给 Client Components
结论
React Server Components 代表了 React 框架的重要发展方向,通过智能地将工作分配到服务器和客户端之间,它为开发者提供了构建更快、更具可扩展性应用的新方法。随着时间的推移,我们可以期待看到基于 RSC 的更多创新模式和工具的出现。
Last updated on