getStaticPaths
使用 getStaticPaths 获取数据并生成静态页面。了解有关 Next.js 中此数据获取 API 的更多信息。
如果一个页面包含动态路由并使用了 getStaticProps,它就需要定义要静态生成的路径列表。
当你从使用动态路由的页面中导出一个名为 getStaticPaths 的函数(静态站点生成,Static Site Generation)时,Next.js 将静态预渲染 getStaticPaths 指定的所有路径。
pages/repo/[name].tsx
import type {
InferGetStaticPropsType,
GetStaticProps,
GetStaticPaths,
} from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getStaticPaths = (async () => {
return {
paths: [
{
params: {
name: 'next.js',
},
}, // 请参阅下面的 "paths" 部分
],
fallback: true, // false 或 "blocking"
}
}) satisfies GetStaticPaths
export const getStaticProps = (async (context) => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}) satisfies GetStaticProps<{
repo: Repo
}>
export default function Page({
repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return repo.stargazers_count
}pages/repo/[name].js
export async function getStaticPaths() {
return {
paths: [
{
params: {
name: 'next.js',
},
}, // 请参阅下面的 "paths" 部分
],
fallback: true, // false 或 "blocking"
}
}
export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}
export default function Page({ repo }) {
return repo.stargazers_count
}getStaticPaths API 参考涵盖了可与 getStaticPaths 一起使用的所有参数和属性。
何时应该使用 getStaticPaths?#
如果你要对使用动态路由的页面进行静态预渲染,并且满足以下条件,就应该使用 getStaticPaths:
- 数据来自 headless CMS
- 数据来自数据库
- 数据来自文件系统
- 数据可以公开缓存(非用户特定)
- 页面必须预渲染(出于 SEO 考虑)且速度非常快 ——
getStaticProps会生成HTML和JSON文件,两者都可以被 CDN 缓存以提升性能
getStaticPaths 何时运行#
getStaticPaths 在生产环境中只在构建期间运行,不会在运行时被调用。你可以使用此工具验证写在 getStaticPaths 中的代码是否已从客户端打包中移除。
相对于 getStaticPaths,getStaticProps 如何运行#
- 对于构建期间返回的任何
paths,getStaticProps会在next build期间运行 - 使用
fallback: true时,getStaticProps在后台运行 - 使用
fallback: blocking时,getStaticProps在初始渲染之前被调用
在哪里可以使用 getStaticPaths#
getStaticPaths必须与getStaticProps一起使用- 你不能将
getStaticPaths与getServerSideProps一起使用 - 你可以从同样使用
getStaticProps的动态路由中导出getStaticPaths - 你不能从非页面文件(例如你的
components文件夹)中导出getStaticPaths - 你必须将
getStaticPaths作为独立函数导出,而不是作为页面组件的属性
在开发环境中每次请求都会运行#
在开发环境中(next dev),getStaticPaths 会在每次请求时被调用。
按需生成路径#
getStaticPaths 允许你控制在构建期间生成哪些页面,而不是通过 fallback 按需生成。在构建期间生成更多页面会导致构建速度变慢。
你可以通过为 paths 返回空数组来推迟所有页面的按需生成。当将 Next.js 应用部署到多个环境时,这尤其有用。例如,你可以让预览环境(而非生产构建)按需生成所有页面,从而加快构建速度。这对于拥有数百/数千个静态页面的网站很有帮助。
pages/posts/[id].js
export async function getStaticPaths() {
// 当此项为 true 时(在预览环境中)不
// 预渲染任何静态页面
// (构建更快,但初始页面加载更慢)
if (process.env.SKIP_BUILD_STATIC_GENERATION) {
return {
paths: [],
fallback: 'blocking',
}
}
// 调用外部 API 端点以获取文章
const res = await fetch('https://.../posts')
const posts = await res.json()
// 根据文章获取我们要预渲染的路径
// 在生产环境中,预渲染所有页面
// (构建更慢,但初始页面加载更快)
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// { fallback: false } 表示其他路由应返回 404
return { paths, fallback: false }
}