简体   繁体   中英

Next.js: getStaticPaths for nested dynamic routes

Imagine you have this data structure:

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

An you have the following route /posts/[postId[/[commentId] so the Next.js structure folder is: posts/[postId]/[commented].js

Then you need to generate the static paths for this routes.

I'm coded the following:

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

But it's not working. The throwed error was:

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.

How I can "map" or "loop" the data to a proper returned format? Thanks in advance!

The problem seems to be that your returning this from getStaticPaths data with a wrong shape:

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

The correct shape is:

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

Just tried this and it works.

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

It generates 3 urls:

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

Is that what you need?

Like mention @Aaron the problem is for double array of filter y el map.

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

Doc 📚 ➡ https://nextjs.org/docs/basic-features/data-fetching#the-paths-key-required

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM