-1

我目前正在制作一个博客网络应用程序,并希望在同一类别中显示帖子。但是,目录 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,
    };
}
4

1 回答 1

0

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

params: { slug: post.node.categories[0].slug }, 
于 2022-01-26T02:47:32.717 回答