【问题标题】:Gatsby GraphQL error: Variable "$slug" is never used in operation "BlogPostQuery"Gatsby GraphQL 错误:变量“$slug”从未在操作“BlogPostQuery”中使用
【发布时间】:2019-02-14 06:19:03
【问题描述】:

我无法使用 Gatsby 提取我的 Ghost 博客的数据。我使用 Ghost 作为我的后端,我使用一个包来获取 Ghost 博客作为源。问题只是在页面上获取单个帖子。这里是blog-post.js

import React from "react";

export default ({ data }) => {
//   const post = data.allGhostPost.edges;
  return (
    <div>
      {/* <h1>{post.title}</h1> */}
      {/* <div dangerouslySetInnerHTML={{ __html: post.html }} /> */}
    </div>
  );
};

export const query = graphql`
  query BlogPostQuery($slug: String!) {
    allGhostPost {
        edges {
          node {
            id
            slug
            title
            html
            published_at
          }
        }
      }
  }
`;

这是我的 gatsby 节点文件:

exports.createPages = ({ graphql, boundActionCreators}) => {
    const {createPage} = boundActionCreators

    return new Promise((resolve, reject) => {
        const blogPostTemplate = path.resolve(`src/templates/blog-post.js`)

        resolve(
            graphql(
                `
                {
                    allGhostPost(sort: { order: DESC, fields: [published_at] }) {
                      edges {
                        node {
                          id
                          slug
                          title
                          html
                          published_at      
                        }
                      }
                    }
                  }
                `
            )
            .then(result => {
                result.data.allGhostPost.edges.forEach(edge => {
                    createPage({
                        path: edge.node.slug,
                        component: blogPostTemplate,
                        context: {
                            slug: edge.node.slug
                        }
                    })
                })
                return;
            })
        )
    })
}

【问题讨论】:

  • 我认为只要不向allGhostPosts提供任何参数,查询确实有未使用的引用,因此是无效的。您是否尝试过完全删除“BlogPostQuery”的参数以及括号?
  • 是的,这行得通。可悲的是,它会返回所有帖子。当我需要蛞蝓提供给我的特定时。我是否没有在我应该的地方包括蛞蝓? @rm-

标签: reactjs graphql gatsby


【解决方案1】:

我发现了我的问题,这是我的查询有问题。对于任何使用 Ghost API 的人。这是您需要的答案:

query BlogPostQuery($slug: String!) {
  allGhostPost(filter: {slug: {eq: $slug}}) {
    edges {
      node {
        id
        slug
        title
        html
        published_at
      }
    }
  }
}

让我解释一下我的答案。

问题是我的 GraphQL 查询不起作用,因为查询中没有使用 $slug 字段。它只是被传入。话虽如此,我必须学习一点 GraphQL 才能得出最终结论。

使用GraphiQL 我发现allGhostPost 有一个filter 方法。使用它我能够得到正确的结果。

【讨论】:

  • 旁注:您的问题并非特定于 Ghost,因为每次查询都会发生这种情况。 filter等功能随处可见:)
猜你喜欢
  • 2022-01-02
  • 2022-01-15
  • 2019-10-25
  • 2021-07-03
  • 2021-10-13
  • 2021-11-20
  • 2021-08-24
  • 2020-01-19
  • 2021-07-22
相关资源
最近更新 更多