首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Next.js:用于嵌套动态路由的getStaticPaths

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

Stack Overflow用户
提问于 2020-10-15 11:55:54
回答 2查看 9.8K关注 0票数 5

假设您有这样的数据结构:

代码语言:javascript
复制
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"
  }]
}

A您有以下路由/posts/[postId[/[commentId],所以Next.js结构文件夹是:posts/[postId]/[commented].js

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

我编码如下:

代码语言:javascript
复制
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
          }
        }
      })
  })
}

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

代码语言:javascript
复制
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.

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-15 12:49:31

问题似乎在于,您从形状错误的getStaticPaths数据中返回这个值:

代码语言:javascript
复制
[
  [ { params: {} }, { params: {} } ],
  [ { params: {} } ]
]

正确的形状是:

代码语言:javascript
复制
[
  { params: {} },
  { params: {} },
  { params: {} }
]

刚试了一下就行了。

代码语言:javascript
复制
    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个urls:

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

这就是你需要的吗?

票数 6
EN

Stack Overflow用户

发布于 2020-10-15 14:53:29

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

代码语言:javascript
复制
 return {
    paths: [
        { params: { id: '1' } },
        { params: { id: '2' } }
      ],
      fallback: ...
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64371066

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档