对于动态路由示例posts/[id].js getStaticPaths 需要定义一个路径列表,以便Next.js 在构建时预渲染所有指定的路径。
函数getStaticPaths 需要返回一个具有paths 属性的对象,该属性是一个包含路由参数和属性fallback 的数组,该属性为真或假。如果 fallback 设置为 false,则任何未从函数 getStaticPaths 返回的路径都不会被预渲染,从而导致 404 页面。
如果您提前知道需要渲染的所有路径,您可以将fallback 设置为 false。这是一个示例..
// getStaticPaths for /category/[slug] where slug can only be -
// either 'category-slug-1', 'category-slug-2' or 'category-slug-3'
export const getStaticPaths = async () => {
return {
paths: [
{ params: { slug: 'category-slug-1'} },
{ params: { slug: 'category-slug-2'} },
{ params: { slug: 'category-slug-3'} }
],
fallback: false // fallback is set to false because we already know the slugs ahead of time
}
}
假设您有一条路线 /posts/[id].js 和来自数据库的 id,并且每天都会创建新帖子。在这种情况下,您可以返回已经存在的路径来预渲染某些页面。并将fallback 设置为true 并根据请求提供页面的后备版本,而不是为未从函数getStaticPaths 返回的路径显示404 页面,然后在后台, nextjs 将为请求的路径调用getStaticProps 并将数据作为JSON 提供,该JSON 将用于在浏览器中呈现页面。
这是一个例子,
export const getStaticPaths = async () => {
const posts = await // your database query or fetch to remote API
// generate the paths
const paths = posts.map(post => ({
params: { id: post.id } // keep in mind if post.id is a number you need to stringify post.id
})
);
return {
paths,
fallback: true
}
}
附: - 当使用fallback 设置为true 时,您需要在NextPage 组件中呈现某种后备组件,否则当您尝试从道具访问数据时,它会抛出类似cannot read property ...x of undefined 的错误
你可以像这样渲染一个后备,
// in your page component
import {useRouter} from 'next/router';
const router = useRouter();
if (router.isFallback) {
return <div>loading...</div>
}