【问题标题】:Next.js: getStaticPaths for nested dynamic routesNext.js:嵌套动态路由的 getStaticPaths
【发布时间】:2021-01-29 21:47:24
【问题描述】:

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

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"
  }]
}

你有以下路线/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
          }
        }
      })
  })
}

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

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.

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

【问题讨论】:

    标签: javascript reactjs next.js static-site-generation


    【解决方案1】:

    问题似乎是您从getStaticPaths 数据返回这个形状错误:

    [
      [ { params: {} }, { params: {} } ],
      [ { params: {} } ]
    ]
    

    正确的形状是:

    [
      { params: {} },
      { params: {} },
      { params: {} }
    ]
    

    刚刚试了一下,效果很好。

        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
          }
        };
    

    它会生成 3 个 url:

    • /posts/post-1/1
    • /posts/post-1/2
    • /posts/post-2/3

    这是你需要的吗?

    【讨论】:

    • 谢谢@Aaron!你让我看到,通过双重映射数组一无所获。我已经在“评论”中有“帖子”的 ID!
    【解决方案2】:

    就像提到@Aaron 一样,问题在于过滤器y el 映射的双数组。

     return {
        paths: [
            { params: { id: '1' } },
            { params: { id: '2' } }
          ],
          fallback: ...
    }
    

    文档?➡https://nextjs.org/docs/basic-features/data-fetching#the-paths-key-required

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 2023-02-10
      • 2021-12-02
      • 2021-09-28
      • 2020-08-27
      • 2022-07-29
      • 2021-03-14
      • 2021-01-20
      相关资源
      最近更新 更多