generateStaticParams
generateStaticParams 函数的 API 参考。
generateStaticParams 函数可与动态路由段配合使用,在构建时静态生成路由,而不是在请求时按需生成。
generateStaticParams 可用于:
TypeScript
// Return a list of `params` to populate the [slug] dynamic segment
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
return posts.map((post) => ({
slug: post.slug,
}))
}
// Multiple versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
// ...
}
JavaScript
// Return a list of `params` to populate the [slug] dynamic segment
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
return posts.map((post) => ({
slug: post.slug,
}))
}
// Multiple versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
export default async function Page({ params }) {
const { slug } = await params
// ...
}
须知:
dynamicParams选项控制是否可以渲染构建时未生成的路径。它仅在不使用 Cache Components 时可用。- 使用
ensureStatic = 'navigation'的动态路由必须返回至少一个 params 对象,并且每个对象都必须包含该路由的所有动态参数。请参阅generateStaticParams错误指南。- 必须从
generateStaticParams返回空数组,或使用export const dynamic = 'force-static',以便重新验证(ISR)运行时的路径。- 在
next dev期间,当您导航到某个路由时,generateStaticParams将被调用。- 在
next build期间,generateStaticParams会在生成相应的布局或页面之前运行。- 在重新验证(ISR)期间,不会再次调用
generateStaticParams。generateStaticParams取代了 Pages Router 中的getStaticPaths函数。
参数
options.params(可选)
如果路由中有多个动态段使用 generateStaticParams,则子级 generateStaticParams 函数会针对父级生成的每一组 params 执行一次。
params 对象包含已填充的 params(来自父级 generateStaticParams),可用于在子段中生成 params。
返回
generateStaticParams 应返回一个对象数组,其中每个对象表示单个路由中已填充的动态段。
- 对象中的每个属性都是该路由需要填充的动态段。
- properties 的 name 是该段的名称,properties 的 value 是该段应被填充的内容。
| 示例路由 | generateStaticParams 返回类型 |
|---|---|
/product/[id] |
{ id: string }[] |
/products/[category]/[product] |
{ category: string, product: string }[] |
/products/[...slug] |
{ slug: string[] }[] |
单个动态段
TypeScript
export function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
// Three versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
// - /product/1
// - /product/2
// - /product/3
export default async function Page({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
// ...
}
JavaScript
export function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
// Three versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
// - /product/1
// - /product/2
// - /product/3
export default async function Page({ params }) {
const { id } = await params
// ...
}
多个动态段
TypeScript
export function generateStaticParams() {
return [
{ category: 'a', product: '1' },
{ category: 'b', product: '2' },
{ category: 'c', product: '3' },
]
}
// Three versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
// - /products/a/1
// - /products/b/2
// - /products/c/3
export default async function Page({
params,
}: {
params: Promise<{ category: string; product: string }>
}) {
const { category, product } = await params
// ...
}
JavaScript
export function generateStaticParams() {
return [
{ category: 'a', product: '1' },
{ category: 'b', product: '2' },
{ category: 'c', product: '3' },
]
}
// Three versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
// - /products/a/1
// - /products/b/2
// - /products/c/3
export default async function Page({ params }) {
const { category, product } = await params
// ...
}
捕获所有动态段
TypeScript
export function generateStaticParams() {
return [{ slug: ['a', '1'] }, { slug: ['b', '2'] }, { slug: ['c', '3'] }]
}
// Three versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
// - /product/a/1
// - /product/b/2
// - /product/c/3
export default async function Page({
params,
}: {
params: Promise<{ slug: string[] }>
}) {
const { slug } = await params
// ...
}
JavaScript
export function generateStaticParams() {
return [{ slug: ['a', '1'] }, { slug: ['b', '2'] }, { slug: ['c', '3'] }]
}
// Three versions of this page will be statically generated
// using the `params` returned by `generateStaticParams`
// - /product/a/1
// - /product/b/2
// - /product/c/3
export default async function Page({ params }) {
const { slug } = await params
// ...
}
示例
预渲染
在构建时生成所有路径
要在构建时静态渲染所有路径,请向 generateStaticParams 提供完整的路径列表:
TypeScript
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
return posts.map((post) => ({
slug: post.slug,
}))
}
JavaScript
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
return posts.map((post) => ({
slug: post.slug,
}))
}
在构建时生成部分路径
要在构建时静态渲染一部分路径,其余路径在运行时首次访问时再渲染,请返回部分路径列表:
TypeScript
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
// Render the first 10 posts at build time
return posts.slice(0, 10).map((post) => ({
slug: post.slug,
}))
}
JavaScript
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
// Render the first 10 posts at build time
return posts.slice(0, 10).map((post) => ({
slug: post.slug,
}))
}
然后,通过使用 dynamicParams 段配置选项,你可以控制当访问一个并非由 generateStaticParams 生成的动态段时会发生什么。
TypeScript
// All posts besides the top 10 will be a 404
export const dynamicParams = false
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
const topPosts = posts.slice(0, 10)
return topPosts.map((post) => ({
slug: post.slug,
}))
}
JavaScript
// All posts besides the top 10 will be a 404
export const dynamicParams = false
export async function generateStaticParams() {
const posts = await fetch('https://.../posts').then((res) => res.json())
const topPosts = posts.slice(0, 10)
return topPosts.map((post) => ({
slug: post.slug,
}))
}
在运行时生成所有路径
要在首次访问时静态渲染所有路径,请返回一个空数组(构建时不会渲染任何路径),或使用 export const dynamic = 'force-static':
export async function generateStaticParams() {
return []
}
须知:
- 必须始终从
generateStaticParams返回一个数组,即使它是空的。否则,该路由将被动态渲染。
export const dynamic = 'force-static'
使用 Cache Components 时
在动态路由中使用 Cache Components 时,generateStaticParams 必须返回至少一个参数。空数组会导致构建错误。这样 Cache Components 就能验证你的路由在运行时不会错误地访问 cookies()、headers() 或 searchParams。
须知:
如果在构建时不知道实际的参数值,你可以返回一个占位参数(例如
[{ slug: '__placeholder__' }])用于验证,然后在页面中使用notFound()处理它。但是,这会妨碍构建时验证有效工作,并可能导致运行时错误。
有关详细演练,请参阅动态路由部分;有关预渲染部分路由并为其余路由提供 App Shell 的内容,请参阅使用 Cache Components 的 ISR。
使用路由处理器时
你可以将 generateStaticParams 与路由处理器一起使用,在构建时静态生成 API 响应:
TypeScript
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export async function GET(
request: Request,
{ params }: RouteContext<'/api/posts/[id]'>
) {
const { id } = await params
// This will be statically generated for IDs 1, 2, and 3
return Response.json({ id, title: `Post ${id}` })
}
JavaScript
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
export async function GET(request, { params }) {
const { id } = await params
// This will be statically generated for IDs 1, 2, and 3
return Response.json({ id, title: `Post ${id}` })
}
结合 Cache Components 的路由处理器
使用 Cache Components 时,结合 use cache 以获得最佳缓存效果:
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }, { id: '3' }]
}
async function getPost(id: Promise<string>) {
'use cache'
const resolvedId = await id
const response = await fetch(`https://api.example.com/posts/${resolvedId}`)
return response.json()
}
export async function GET(
request: Request,
{ params }: RouteContext<'/api/posts/[id]'>
) {
const post = await getPost(params.then((p) => p.id))
return Response.json(post)
}
更多详情,请参阅路由处理器文档。
禁用未指定路径的渲染
要防止未指定的路径在运行时被预渲染,请在路由段中添加 export const dynamicParams = false 选项。使用此配置选项时,只会提供由 generateStaticParams 提供的路径,未指定的路由将返回 404 或匹配(在全捕获路由的情况下)。
路由中的多个动态段
你可以为当前布局或页面之上的动态段生成参数,但不能为之下的动态段生成。例如,给定 app/products/[category]/[product] 路由:
app/products/[category]/[product]/page.js可以同时为[category]和[product]生成参数。app/products/[category]/layout.js只能为[category]生成参数。
为具有多个动态段的路由生成参数有两种方法:
自下而上生成参数
从子路由段生成多个动态段。
TypeScript
// Generate segments for both [category] and [product]
export async function generateStaticParams() {
const products = await fetch('https://.../products').then((res) => res.json())
return products.map((product) => ({
category: product.category.slug,
product: product.id,
}))
}
export default function Page({
params,
}: {
params: Promise<{ category: string; product: string }>
}) {
// ...
}
JavaScript
// Generate segments for both [category] and [product]
export async function generateStaticParams() {
const products = await fetch('https://.../products').then((res) => res.json())
return products.map((product) => ({
category: product.category.slug,
product: product.id,
}))
}
export default function Page({ params }) {
// ...
}
自上而下生成参数
先生成父段,再使用其结果生成子段。
TypeScript
// Generate segments for [category]
export async function generateStaticParams() {
const products = await fetch('https://.../products').then((res) => res.json())
return products.map((product) => ({
category: product.category.slug,
}))
}
export default function Layout({
params,
}: {
params: Promise<{ category: string }>
}) {
// ...
}
JavaScript
// Generate segments for [category]
export async function generateStaticParams() {
const products = await fetch('https://.../products').then((res) => res.json())
return products.map((product) => ({
category: product.category.slug,
}))
}
export default function Layout({ params }) {
// ...
}
父级 generateStaticParams 每生成一个段,子路由段的 generateStaticParams 函数就会执行一次。
子级 generateStaticParams 函数可以使用父级 generateStaticParams 函数返回的 params 来动态生成自己的段。
TypeScript
// Generate segments for [product] using the `params` passed from
// the parent segment's `generateStaticParams` function
export async function generateStaticParams({
params: { category },
}: {
params: { category: string }
}) {
const products = await fetch(
`https://.../products?category=${category}`
).then((res) => res.json())
return products.map((product) => ({
product: product.id,
}))
}
export default function Page({
params,
}: {
params: Promise<{ category: string; product: string }>
}) {
// ...
}
JavaScript
// Generate segments for [product] using the `params` passed from
// the parent segment's `generateStaticParams` function
export async function generateStaticParams({ params: { category } }) {
const products = await fetch(
`https://.../products?category=${category}`
).then((res) => res.json())
return products.map((product) => ({
product: product.id,
}))
}
export default function Page({ params }) {
// ...
}
请注意,params 参数可以同步访问,并且只包含父段的参数。
须知:
当父级动态段是根参数时,你也可以通过从
next/root-params模块中调用其 getter,在嵌套的generateStaticParams中读取它。
为了获得类型补全,你可以将 TypeScript 的 Awaited 辅助类型与 Page Props helper 或 Layout Props helper 结合使用:
export async function generateStaticParams({
params: { category },
}: {
params: Awaited<LayoutProps<'/products/[category]'>['params']>
}) {
const products = await fetch(
`https://.../products?category=${category}`
).then((res) => res.json())
return products.map((product) => ({
product: product.id,
}))
}
须知:
对于相同的数据,
fetch请求会在所有以generate为前缀的函数、Layouts、Pages 和服务器组件中自动记忆化。如果fetch不可用,可以使用 React 的cache。
版本历史
| 版本 | 变更 |
|---|---|
v13.0.0 |
引入 generateStaticParams。 |