一. Next.js 是围绕着 页面(pages) 的概念构造的。
一个页面(page)就是一个从 pages
目录下的 .js
、.jsx
、.ts
或 .tsx
文件导出的 React 组件。
页面(page) 根据其文件名与路由关联。例如,pages/about.js
被映射到 /about
。
甚至可以在文件名中添加动态路由参数。
二. 具有动态路由的页面
创建了一个命名为 pages/posts/[id].js
的文件,那么就可以通过 posts/1
、posts/2
等类似的路径进行访问。
三. 预渲染
静态生成(Static Generation) 和 服务器端渲染(Server-side Rendering)
Next.js 允许你为每个页面 选择 预渲染的方式。
四. 页面中获取数据
- 页面 内容 取决于外部数据:使用
getStaticProps
。 - 页面 paths(路径) 取决于外部数据:使用
getStaticPaths
(通常还要同时使用getStaticProps
)。// TODO: 需要获取 `posts`(通过调用 API ) // 在此页面被预渲染之前 function Blog({ posts }) { return ( <ul> {posts.map((post) => ( <li>{post.title}</li> ))} </ul> ) } // 此函数在构建时被调用 export async function getStaticProps() { // 调用外部 API 获取博文列表 const res = await fetch('https://.../posts') const posts = await res.json() // 通过返回 { props: { posts } } 对象,Blog 组件 // 在构建时将接收到 `posts` 参数 return { props: { posts, }, } } export default Blog
// 此函数在构建时被调用 export async function getStaticPaths() { // 调用外部 API 获取博文列表 const res = await fetch('https://.../posts') const posts = await res.json() // 据博文列表生成所有需要预渲染的路径 const paths = posts.map((post) => ({ params: { id: post.id }, })) // We'll pre-render only these paths at build time. // { fallback: false } means other routes should 404. return { paths, fallback: false } } // 在构建时也会被调用 export async function getStaticProps({ params }) { // params 包含此片博文的 `id` 信息。 // 如果路由是 /posts/1,那么 params.id 就是 1 const res = await fetch(`https://.../posts/${params.id}`) const post = await res.json() // 通过 props 参数向页面传递博文的数据 return { props: { post } } }