返回博客列表
React Server Components 深度解析
ReactServer ComponentsNext.js

React Server Components 深度解析

👤 React Team📅 ⏱️ 12 分钟阅读

React Server Components 深度解析 ⚡


React Server Components 是 React 18 引入的一个革命性功能,它改变了我们构建 React 应用的方式。


🤔 什么是 Server Components?


Server Components 是在服务器上渲染的 React 组件,它们可以:


  • 直接访问服务器资源(数据库、文件系统等)
  • 减少客户端 JavaScript 包大小
  • 提供更好的性能和 SEO

  • 🆚 Server Components vs Client Components


    Server Components

  • 在服务器上运行
  • 可以直接访问后端资源
  • 不能使用浏览器 API
  • 不能使用 useState、useEffect 等 hooks
  • 默认情况下是 Server Components

  • Client Components

  • 在浏览器中运行
  • 可以使用所有 React hooks
  • 可以处理用户交互
  • 需要 "use client" 指令

  • 🚀 在 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. 数据获取

  • 在 Server Components 中进行数据获取
  • 利用 React 18 的并发特性

  • tsx

    async 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. 组件边界

  • 明确区分 Server 和 Client Components
  • 使用 TypeScript 获得更好的类型安全

  • 2. 性能监控

  • 使用 Next.js 内置的性能分析工具
  • 监控 Server Components 的渲染时间

  • 🌟 总结


    React Server Components 为我们提供了:


  • **更好的性能**:减少客户端 JavaScript
  • **更简单的数据获取**:直接在组件中获取数据
  • **更好的 SEO**:服务器端渲染
  • **更灵活的架构**:Server 和 Client 的完美结合

  • Server Components 是 React 和 Next.js 的未来,掌握它们将让你的应用更加高效和现代化! 🚀


    📚 其他文章