簡體   English   中英

Gatsby GraphQL錯誤:變量“ $ slug”從未在操作“ BlogPostQuery”中使用

[英]Gatsby GraphQL error: Variable “$slug” is never used in operation “BlogPostQuery”

我無法使用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方法。 使用它,我可以得出正確的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM