【问题标题】:Error: A required parameter (slug) was not provided as a string in getStaticPaths for /categories/[slug]错误:在 /categories/[slug] 的 getStaticPaths 中未将必需参数 (slug) 作为字符串提供
【发布时间】:2022-01-26 10:47:32
【问题描述】:

我目前正在制作一个博客网络应用程序,并希望显示同一类别的帖子。 但是,目录 category/[slug.id] 中关于 GraphQL 的 NextJS 动态路由似乎存在问题。问题本身应该很简单,但我一生都无法弄清楚出了什么问题。显示的错误是

error - Error: A required parameter (slug) was not provided as a string in getStaticPaths for /category/[slug]

以下是与错误相关的所有必要功能。作为一个侧节点,我在同一目录下也有 blog/[slug.id],这是我第一次处理动态 GraphQL 路由。

查询博客中所有相关分类的功能:

export const getAllCategories = async () => {
  const query = gql`
  query MyQuery {
    postsConnection {
      edges {
        node {
          categories {
            name
            slug
          }
        }
      }
    }
  }
    `
  const results = await request(graphqlAPI, query);
  return results.postsConnection.edges;
};

获取所有带有类别 slug 的帖子的功能:

export const getSimilarPosts = async (slug) => {
  const query = gql`
  query MyQuery {
    posts(where: {categories_some: {slug: "$slug"}}) {
      featuredImage {
        url
      }
      createdAt
      slug
      title
    }
  }
  `;
  const result = await request(graphqlAPI, query, { slug });

  return result.posts;
};

静态路径和静态道具功能:

export async function getStaticProps({ params }) {
    const post = await getSimilarPosts(params.slug);
    return {
        props: { post },
    };
} 

export async function getStaticPaths() {
    const posts = await getAllCategories();
    const paths = posts.map((post) => ({
        params: { slug: post.node.categories.slug }, 
      }));
    return {
        paths: paths,
        fallback: false,
    };
}

【问题讨论】:

    标签: reactjs graphql next.js nextjs-dynamic-routing


    【解决方案1】:

    找到了答案,这可以通过将 getStaticPaths 函数中的 params 部分更改为轻松解决

    params: { slug: post.node.categories[0].slug }, 
    

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 2021-08-26
      • 2021-10-05
      • 2021-12-12
      • 2021-07-23
      • 2023-02-12
      • 2019-06-21
      • 2017-03-31
      • 2019-09-16
      相关资源
      最近更新 更多