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>;
}