代码示例
1. 项目结构
/app
/page.tsx // 入口页面,服务器组件
/components
/PostList.tsx // 服务器组件,渲染文章列表
/lib
/posts.ts // 模拟获取文章数据的函数(服务器端)
2. 模拟服务器数据获取(/lib/posts.ts
)
export type Post = {
id: number;
title: string;
content: string;
};
const posts: Post[] = [
{ id: 1, title: "Next.js 13 Server Components 深入解析", content: "详细介绍Next.js 13的服务器组件机制..." },
{ id: 2, title: "React 18 新特性总结", content: "Concurrent Mode, Suspense等新功能..." },
{ id: 3, title: "TypeScript 类型魔法大全", content: "高级类型技巧,条件类型等..." },
];
// 模拟异步请求,真实项目中可换成数据库或API调用
export async function getPosts(): Promise<Post[]> {
await new Promise((r) => setTimeout(r, 500)); // 模拟延迟
return posts;
}