Composing Client and Server Components

Thu Jul 11 2024

Author's profile picture

tye25

Composing Client and Server Components 是 React 18 中引入的一个重要概念,允许开发者在同一个应用中混合使用客户端和服务器端组件。这种方法旨在结合两种组件类型的优势,以提高应用性能和开发体验。让我为您概述这个概念:

  1. 服务器组件(Server Components):
    • 在服务器上渲染
    • 可以直接访问服务器资源(如数据库)
    • 不包含交互逻辑
    • 减少客户端 JavaScript 包的大小
  2. 客户端组件(Client Components):
    • 在浏览器中渲染
    • 可以包含状态和交互逻辑
    • 可以使用浏览器 API

组合这两种组件的基本原则:

  1. 默认使用服务器组件
  2. 仅在需要客户端交互或浏览器 API 时使用客户端组件
  3. 服务器组件可以导入并渲染客户端组件
  4. 客户端组件不能导入服务器组件,但可以将服务器组件作为 props 接收

示例:

// ServerComponent.js (服务器组件)
importClientComponentfrom'./ClientComponent';
export default async function ServerComponent(){
    const data =await fetchDataFromDatabase();
    return (<div><h1>Server-rendered data:</h1><pre>{JSON.stringify(data,null,2)}</pre><ClientComponent/></div>);}
// ClientComponent.js (客户端组件)
'use client';
import{ useState }from'react';
exportdefaultfunctionClientComponent(){
    const[count, setCount]=useState(0);
    return(<buttononClick={()=>setCount(count +1)}> Clicked {count} times</button>);}

在这个例子中,ServerComponent 从数据库获取数据并渲染,同时它也包含了一个 ClientComponent,后者处理客户端交互。

使用这种组合方法的优势:

  1. 性能优化:减少客户端 JavaScript 包的大小
  2. 更好的数据获取:直接在服务器上获取数据
  3. 自动代码分割:客户端组件自动成为单独的 JavaScript 包
  4. 改善初始加载时间:服务器组件可以更快地渲染初始内容