【问题标题】:Error: getStaticPaths is required for dynamic SSG pages and is missing for "xxx". NextJS错误:动态 SSG 页面需要 getStaticPaths,而“xxx”缺少 getStaticPaths。 NextJS
【发布时间】:2021-04-23 06:18:43
【问题描述】:
当我尝试在 NextJS 中创建页面时,我收到此错误 "Error: getStaticPaths is required for dynamic SSG pages and is missing for 'xxx'"。
我不想在构建时生成任何静态页面。那么为什么我需要创建一个'getStaticPaths' 函数呢?
【问题讨论】:
标签:
reactjs
next.js
server-side-rendering
static-site
ssg
【解决方案1】:
如果您正在创建一个动态页面,例如:product/[slug].tsx,那么即使您不想在构建时创建任何页面,您也需要创建一个 getStaticPaths 方法来设置 fallback 属性并让 NextJS 知道当您尝试获取的页面不存在时该怎么办。
export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {
return {
paths: [], //indicates that no page needs be created at build time
fallback: 'blocking' //indicates the type of fallback
}
}
getStaticPaths主要做两件事:
【解决方案2】:
动态路由 Next Js
页面/用户/[id].js
import React from 'react'
const User = ({ user }) => {
return (
<div className="row">
<div className="col-md-6 offset-md-3">
<div className="card">
<div className="card-body text-center">
<h3>{user.name}</h3>
<p>Email: {user.email} </p>
</div>
</div>
</div>
</div>
)
}
export async function getStaticPaths() {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const users = await res.json()
const paths = users.map((user) => ({
params: { id: user.id.toString() },
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${params.id}`)
const user = await res.json()
return { props: { user } }
}
export default User
【解决方案3】:
对于渲染动态路由,使用getServerSideProps() 而不是getStaticProps()
例如:
export async function getServerSideProps({
locale,
}: GetServerSidePropsContext): Promise<GetServerSidePropsResult<Record<string, unknown>>> {
return {
props: {
...(await serverSideTranslations(locale || 'de', ['common', 'employees'], nextI18nextConfig)),
},
}
}
You can check here as well
【解决方案4】:
如果你使用getStaticPaths,你就是在告诉 next.js 你想预生成那个页面。但是,由于您在动态页面中使用它,next.js 事先并不知道它必须创建多少页面。
使用getStaticPaths,我们获取数据库。如果我们正在渲染博客,我们会获取数据库来决定我们有多少博客,idOfBlogPost 会是什么,然后基于这些信息,getStaticPath 将预先生成页面。
另外,getStaticProps 不仅仅在构建期间运行。如果添加revalidate:numberOfSeconds,next.js 将在 "numberOfSeconds" 时间后使用新数据重新创建新页面。