【问题标题】:Error 'getStaticPaths can only be used with dynamic pages, not '/'' with Next JS错误“getStaticPaths 只能用于动态页面,不能用于 Next JS”
【发布时间】:2021-07-22 12:39:16
【问题描述】:

我想为我的帖子博客使用 getStaticPaths 并使用动态路由,但在构建时出现错误。

我的动态路由文件夹:

页面/文章/[类别]/[slug].js

我的链接导航:

    <Link href={`/article/${category}/${slug}`} passHref>
      <Card>
        ...some data
      </Card>
    <Link />

我的 getStaticPaths:

export async function getStaticPaths () {
   
  // retrieve data from cms

  const data = await getAllPreviewPosts()

  // generate the paths

  const paths = data.map( ({ fields: { slug , stackName } }) => ({ 
   params: { category: stackName, slug: slug } 
   }))

  return {
     paths, 
     fallback: false
  }   
}

export async function getStaticProps () {
 /* ... get data from cms */
}

但是当我运行npm run build 时,我得到了这个错误:

Error: getStaticPaths can only be used with dynamic pages, not '/'.

【问题讨论】:

  • getStaticPaths 在哪个文件中?

标签: next.js dynamic-routing getstaticpaths


【解决方案1】:

getStaticPaths 定义导出时 next.js 必须呈现哪些页面。它用于生成所有可用的动态路由。您不能在页面本身上使用该数据。

要让所有可用的类别和 slugs 在您的导航组件中使用它,您需要使用 getStaticProps 来加载页面上的数据并将其作为道具传递到您的导航组件中。

你可以在这里找到一个例子:https://github.com/vercel/next.js/blob/master/examples/with-static-export/pages/index.js

【讨论】:

    猜你喜欢
    • 2014-12-17
    • 2021-04-23
    • 2021-07-23
    • 2021-08-05
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多