Next.js
Next.js 是一个基于 React 的全栈开发框架,提供了服务端渲染、静态生成、API 路由等强大功能。
核心特性
1. 路由系统
Next.js 14 引入了全新的 App Router,基于 React Server Components:
// app/page.tsx - 页面组件
export default function HomePage() {
return <h1>Welcome to Next.js</h1>;
}
// app/blog/[slug]/page.tsx - 动态路由
export default function BlogPost({ params }: { params: { slug: string } }) {
return <h1>Post: {params.slug}</h1>;
}
// app/layout.tsx - 布局组件
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html>
<body>{children}</body>
</html>
);
}
2. 数据获取
// 服务端组件中获取数据
async function getData() {
const res = await fetch('https://api.example.com/data', {
next: { revalidate: 3600 } // 增量静态再生成
});
return res.json();
}
export default async function Page() {
const data = await getData();
return <main>{/* 使用数据 */}</main>;
}
// 客户端数据获取
'use client';
import { useQuery } from '@tanstack/react-query';
export default function ClientComponent() {
const { data } = useQuery({
queryKey: ['todos'],
queryFn: () => fetch('/api/todos').then(res => res.json()),
});
return <div>{/* 使用数据 */}</div>;
}
3. 服务器组件
// 服务器组件(默认)
export default async function ServerComponent() {
const data = await getData(); // 直接在服务器端获取数据
return <div>{data.title}</div>;
}
// 客户端组件
'use client';
export default function ClientComponent() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
4. API 路由
// app/api/users/route.ts
import { NextResponse } from 'next/server';
export async function GET() {
const users = await getUsers();
return NextResponse.json(users);
}
export async function POST(request: Request) {
const data = await request.json();
const newUser = await createUser(data);
return NextResponse.json(newUser, { status: 201 });
}
Pages Router(传统版本)
1. 基础路由
// pages/index.tsx - 首页
export default function Home() {
return <h1>Welcome to Next.js</h1>;
}
// pages/posts/[id].tsx - 动态路由
export default function Post({ post }) {
return (
<article>
<h1>{post.title}</h1>
<div>{post.content}</div>
</article>
);
}
// 获取动态路由参数
export async function getStaticPaths() {
const posts = await getPosts();
return {
paths: posts.map((post) => ({
params: { id: post.id },
})),
fallback: false,
};
}
export async function getStaticProps({ params }) {
const post = await getPost(params.id);
return {
props: {
post,
},
};
}