"Error: getStaticPaths is required for dynamic SSG pages and is missing for 'xxx'"当我尝试在 NextJS 中创建我的页面时出现此错误。
我不想在构建时生成任何静态页面。那么为什么我需要创建一个'getStaticPaths'函数呢?
"Error: getStaticPaths is required for dynamic SSG pages and is missing for 'xxx'"当我尝试在 NextJS 中创建我的页面时出现此错误。
我不想在构建时生成任何静态页面。那么为什么我需要创建一个'getStaticPaths'函数呢?
如果您正在创建一个动态页面,例如: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 主要做两件事:
指示应该在构建时创建哪些路径(返回一个paths数组)
指示当某个页面(例如:“product/myProduct123”在 NextJS 缓存中不存在时要执行的操作(返回fallback类型)
动态路由 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
用于渲染动态路由使用  getServerSideProps()而不是getStaticProps()
例如:
export async function getServerSideProps({
locale,
}: GetServerSidePropsContext): Promise<GetServerSidePropsResult<Record<string, unknown>>> {
return {
    props: {
        ...(await serverSideTranslations(locale || 'de', ['common', 'employees'], nextI18nextConfig)),
    },
  }
}
如果您正在使用getStaticPaths,则是在告诉 next.js 您想要预生成该页面。但是,由于您在动态页面中使用了它,因此 next.js 事先不知道它必须创建多少个页面。
使用getStaticPaths,我们获取数据库。如果我们正在渲染博客,我们会获取数据库来决定我们有多少博客,会是什么idOfBlogPost,然后根据这些信息,getStaticPath将预先生成页面。
此外,getStaticProps不仅在构建期间运行。如果添加revalidate:numberOfSeconds,next.js 将在“numberOfSeconds”时间后使用新数据重新创建新页面。