Next.js:嵌套动态路由的 getStaticPaths

Car*_*tre 6 javascript reactjs next.js static-site-generation

想象一下你有这样的数据结构:

const data = {
  posts: [{
    id: 1,
    title: "Post 1"
    slug: "post-1"
  }, {
    id: 2,
    title: "Post 2"
    slug: "post-2"
  }],

  comments: [{
    id: 1,
    postId: "post-1",
    text: "Comment 1 for Post 1"
  }, {
    id: 2,
    postId: "post-1",
    text: "Comment 2 for Post 1"
  }, {
    id: 3,
    postId: "post-2",
    text: "Comment 1 for Post 2"
  }]
}
Run Code Online (Sandbox Code Playgroud)

您有以下路线/posts/[postId[/[commentId] ,因此 Next.js 结构文件夹为:posts/[postId]/[commented].js

然后您需要为此路由生成静态路径。

我的编码如下:

export async function getStaticPaths() {
  const { posts, comments } = data
  const paths = posts.map((post) => {
    return comments
      .filter((comment) => comment.postId === post.slug)
      .map((comment) => {
        return {
          params: {
            postId: post.slug,
            commentId: comment.id
          }
        }
      })
  })
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用。抛出的错误是:

Error: Additional keys were returned from `getStaticPaths` in page "/clases/[courseId]/[lessonId]". URL Parameters intended for this dynamic route must be nested under the `params` key, i.e.:

        return { params: { postId: ..., commentId: ... } }

Keys that need to be moved: 0, 1.
Run Code Online (Sandbox Code Playgroud)

如何将数据“映射”或“循环”为正确的返回格式?提前致谢!

小智 8

问题似乎是您从getStaticPaths形状错误的数据中返回此值:

[
  [ { params: {} }, { params: {} } ],
  [ { params: {} } ]
]
Run Code Online (Sandbox Code Playgroud)

正确的形状是:

[
  { params: {} },
  { params: {} },
  { params: {} }
]
Run Code Online (Sandbox Code Playgroud)

刚刚尝试过这个并且有效。

    export async function getStaticPaths() {
      const paths = data.comments.map((comment) => {
        return {
          params: {
            postId: comment.postId,
            commentId: comment.id
          }
        }
      });
    
      console.log(paths);
    
      return {
        paths,
        fallback: false
      }
    };
Run Code Online (Sandbox Code Playgroud)

它生成 3 个 url:

  • /帖子/post-1/1
  • /帖子/post-1/2
  • /帖子/post-2/3

这是你需要的吗?