【问题标题】:Gatsby & Contentful Querying盖茨比和内容查询
【发布时间】:2019-06-17 11:40:23
【问题描述】:

我很难找到准确描述如何使用“gatsby-source-contentful”插件和从内容 API 查询数据的文档。我在 gatsby-config.js 文件中设置了所有内容,并且没有运行错误。我想知道如何开始拨打这些电话。我查看了 /___graphql 路径,没有看到任何与内容相关的查询选项。

任何信息将不胜感激。

这是我的插件配置数据

{
   resolve: `gatsby-source-contentful`,
   options: {
     spaceId: keys.spaceId,
     accessToken: keys.accessToken,
   },
},

【问题讨论】:

    标签: gatsby contentful


    【解决方案1】:

    您的 gatsby-config 文件似乎没问题(如果您的 accessToken 有效,则没有错误)。试试这个示例查询以从 Contentful 中检索数据:

    export const pageQuery = graphql`
      query HomeQuery {
        allContentfulBlogPost(sort: { fields: [publishDate], order: DESC }) {
          edges {
            node {
              title
              slug
              publishDate(formatString: "MMMM Do, YYYY")
              tags
              heroImage {
                sizes(maxWidth: 350, maxHeight: 196, resizingBehavior: SCALE) {
                 ...GatsbyContentfulSizes_tracedSVG
                }
              }
              description {
                childMarkdownRemark {
                  html
                }
              }
            }
          }
        }
        allContentfulPerson(filter: { id: { eq: "c15jwOBqpxqSAOy2eOO4S0m" } }) {
          edges {
            node {
              name
              shortBio {
                shortBio
              }
              title
              heroImage: image {
                sizes(
                  maxWidth: 1180
                  maxHeight: 480
                  resizingBehavior: PAD
                  background: "rgb:000000"
                ) {
                  ...GatsbyContentfulSizes_tracedSVG
                }
              }
            }
          }
        }
      }
    `
    

    在页面内部,您可以通过这种方式访问​​数据:

    const siteTitle = this.props.data.site.siteMetadata.title;
    const posts = this.props.data.allContentfulBlogPost.edges;
    const [author] = this.props.data.allContentfulPerson.edges;
    

    【讨论】:

    • 我在类型 Query 上收到错误 GraphQL 错误未知字段 allContentfulBlogPost
    • @JoshBowden,创建此查询后,您需要重新启动 gatsby(仅热重载不起作用)。您需要重新启动 gatsby 开发过程。你这样做了吗?
    • 通过一些挖掘,我得到了“GraphQL 不适用于我的帐户”的错误。这是否意味着免费的 contentful 层不允许我使用 graphQL 访问数据?
    • @JoshBowden 你在这方面做得怎么样?
    • 您可以将 GQL 与 Contentful 免费层一起使用。我有超过 15 个内容模型和很多非常适合查询的内容。正如 Aldo 上面提到的,您必须重新启动开发服务器,但我认为您还必须刷新缓存。所以我总是(从项目的根)运行的是gatsby clean && yarn start。如果有人对如何更好、更流畅地执行此操作有任何意见,请分享。
    猜你喜欢
    • 2020-12-16
    • 2018-10-14
    • 2020-05-23
    • 1970-01-01
    • 2018-10-18
    • 2020-04-20
    • 1970-01-01
    • 2021-04-25
    • 2020-05-29
    相关资源
    最近更新 更多