【问题标题】:How to use multiple nested dynamic routes with getStaticPaths?如何通过 getStaticPaths 使用多个嵌套动态路由?
【发布时间】:2020-08-27 03:50:14
【问题描述】:

这是我的页面树

├── _app.tsx
├── _document.tsx
├── index.tsx
└── [type]
    └── [slug].tsx

这是 [slug] 页面的 getStaticPaths:

export const getStaticPaths: GetStaticPaths = async () => {
  const posts = getAllPosts(["slug"]);

  return {
    paths: posts.map((posts) => {
      return {
        params: {
          type: posts.mainTag,
          slug: posts.slug,
        },
      };
    }),
    fallback: false,
  };
};

例如,页面看起来像这样 http://localhost:3000/programming/some-slug

当我转到某个帖子时,我收到此错误:

在 getStaticPaths 中没有为 /[type]/[slug] 提供所需的参数(类型)

我只是不知道如何将type 参数提供给路由器。

【问题讨论】:

  • 似乎posts.mainTag 可能不是一个字符串 - 你能验证它不是一个对象/空等:console.info(typeof posts.mainTag) 在你的地图循环中
  • 它是安全输入的,它是一个字符串。
  • 所有帖子都有mainTag?一个失踪将是一个概率
  • 我查了,每个帖子都有一个“programming”的mainTag
  • 上面的示例代码很好,直觉告诉我数据是一个问题。也许用一个简单的数组替换 getAllPosts(["slug"]); 以进行三重检查:const posts = [ { mainTag: 'programming', slug: 'hello-world' }, { mainTag: 'programming', slug: 'nextjs-101' }, ];

标签: reactjs next.js


【解决方案1】:

上面的示例代码似乎正确,所以我会尝试两件事:

1) 我在调用 getAllPosts(["slug"]) 时没有看到 await 前缀 - 这意味着您在获得数据之前就返回了。

除非是设计,否则改为:

const posts = await getAllPosts(["slug"]);

2) 可能存在数据问题,并且您缺少预期的属性。我建议你用一个简单的数组替换getStaticPaths

const Test = (props) => {
    return (
       <>
           {props.slug}
       </>
    );
};

export async function getStaticProps({params}) {
    return {
        props: params
    }
}

export async function getStaticPaths() {
    const posts = [
        {
            mainTag: 'programming',
            slug: 'hello-world'
        },
        {
            mainTag: 'programming',
            slug: 'nextjs-101'
        },
    ];

    return {
        paths: posts.map((posts) => {
            return {
                params: {
                    type: posts.mainTag,
                    slug: posts.slug,
                },
            };
        }),
        fallback: false,
    };
}

export default Test;

【讨论】:

  • 好吧 samuel,你一直都是对的,mainTag 没有从 getAllPosts() 函数正确传递。在我硬编码值之后,就像你一样。有用。非常感谢。
猜你喜欢
  • 2021-01-29
  • 2023-02-10
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
  • 2021-01-20
  • 1970-01-01
相关资源
最近更新 更多