使用 Next.js 导出静态页面,我在动态路由中得到它,如 pages/[id].js
我在 getStaticPaths
中放入的任何路径部分将被创建。凉爽的。
列出每个页面是否更好:
getStaticPaths(){
return (
// some function to spit out a list of every possible page
)
}
或者
getStaticPaths(){
return (
// some function to return the next and previous page
)
}
或者这有关系吗?
最佳答案
对于动态路由示例 posts/[id].js
getStaticPaths
需要定义一个路径列表,以便 Next.js
在构建时预渲染所有指定的路径。
函数getStaticPaths
需要返回一个带有 paths
的对象属性是一个包含路由参数和属性 fallback
的数组这将是真的还是假的。如 fallback
对于未从函数 getStaticPaths
返回的任何路径设置为 false不会被预渲染因此导致 404
页。
如果您知道需要提前渲染的所有路径,您可以设置 fallback
为假。这是一个例子..
// 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
并且根据要求,Next.js 将提供页面的后备版本,而不是显示 404
未从函数返回的路径的页面 getStaticPaths
,然后在后台,nextjs 会调用 getStaticProps
对于请求的路径,并将数据作为 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
中呈现某种回退组件否则当你尝试从 props 访问数据时,它会抛出类似 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>
}
关于static - next.js getStaticPaths 列出每条路径还是仅列出附近的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62057131/