reactjs - Gatsby GraphQL 错误 : Variable "$slug" is never used in operation "BlogPostQuery"

标签 reactjs graphql gatsby

我无法使用 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;
            })
        )
    })
}

最佳答案

我发现了我的问题,这是我的查询的问题。适用于使用 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 方法。使用它我能够得出正确的结果。

关于reactjs - Gatsby GraphQL 错误 : Variable "$slug" is never used in operation "BlogPostQuery",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52247203/

相关文章:

javascript - Prop 在异常情况下丢失

javascript - redux 如何使用 react-router 在 componentWillMount 上重定向

angular - 使用 angular-apollo graphql 客户端获取 404 Not Found

gatsby - 配置 gatsby-transformer-remark 添加默认类

javascript - 浏览器中的静态页面 Gatsby?

reactjs - 如何将 React 与 Typescript 和 SASS 结合使用

reactjs - 通过 POST 从 React 获取数据到 Flask

javascript - 绝对路径在 Gatsby 图像中不起作用?

reactjs - Apollo 客户端 3 从缓存中逐出对象

javascript - GraphQL 参数如何与字段关联?