0

我目前正在创建一个博客 Web 应用程序,并希望显示当前类别中的所有帖子,当前目录为 [slug].js/category。但是,即使一切似乎都运行良好,getStaticProps 也没有返回任何数据。getStaticProps 和 getStaticPaths 如下所示:


export async function getStaticPaths() {
    const categories = await getCategories();
    console.log(categories);

// [
//   { name: 'Web Development', slug: 'webdev' },
//   { name: 'Machine Learning', slug: 'ml' }
// ]

    const paths = categories.map((post) => ({
        params: { slug: post.slug }, 
      }));
    console.log(paths)

// [ { params: { slug: 'webdev' } }, { params: { slug: 'ml' } } ]

    return {
        paths: paths,
        fallback: true,
    };
}

export async function getStaticProps({ params }) {
    console.log(params.slug); // (webdev or ml depending on slug)
    const data = await getSimilarPosts(params.slug);
    console.log(data); // []
    return {
        props: { post: data },
    };
} 

如上面的代码所示,params.slug 返回预期的 slug。但是,将其作为参数传递给 getSimilarPosts 不会产生所需的数据,这很奇怪。

查询类别中相似帖子(getSimilarPosts)的功能是:

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

API 函数工作正常,因为手动查询它(slug:“webdev”)返回预期的数据对象。getStaticProps 似乎有问题。

4

0 回答 0