场景描述
一个简单的博客首页,服务端组件流式渲染文章列表和用户信息。文章列表数据较大,流式逐步加载,提升首次内容展示速度。
代码示例
1. Server Component (app/page.jsx)
import React from "react";
// 模拟异步获取文章列表(大数据量,延迟)
async function fetchPosts() {
const posts = [
{ id: 1, title: "React Server Components 介绍" },
{ id: 2, title: "流式传输提高性能" },
{ id: 3, title: "实战示例代码详解" },
// 模拟更多数据
];
for (let post of posts) {
await new Promise((r) => setTimeout(r, 1000)); // 模拟网络延迟
yield post;
}
}
// 文章列表组件,支持流式yield
async function* Posts() {
yield <h2>文章列表:</h2>;
for await (const post of fetchPosts()) {
yield <p key={post.id}>{post.title}</p>;
}
}
// 用户信息,模拟即时加载
async function UserInfo() {
await new Promise((r) => setTimeout(