盖茨比 GraphQL 问题

Gatsby GraphQL issue

我对 Gatsby 比较陌生。我使用 Strapi 作为后端,在我的前端 Gatsby 中,在 GraphQL 游乐场中,我正在执行以下查询并获得预期结果:

query MyQuery {
  strapiAssessment {
    title
    rating {
      id
      topic
      rate
    }
  }
}

在我的 Gatsby 前端代码中,我有以下内容:

import React from "react"
import Title from "../components/Title"
import { graphql } from "gatsby"

const SelfAssesment = ({ data }) => {
  const {
    strapiAssessment: { title, rating },
  } = data
  console.log(data)
  return (
    <section className="section jobs">
      <Title title={title} />
      <div className="about-stack">
        <p>Rankning i olika teknologier:</p>
        {rating.map(item => {
          return <span key={item.id}>{item.topic}</span>
        })}
      </div>
      <div className="about-stack">
        {rating.map(item => {
          return <span key={item.id}>{item.rate}</span>
        })}
      </div>
    </section>
  )
}

export const query = graphql`
  {
    strapiAssessment {
      title
      rating {
        id
        topic
        rate
      }
    }
  }
`

export default SelfAssesment

我收到以下错误:

我没有定义,我有什么地方没有申报或有错字吗?

您是 运行 不在顶级 (components/SelfAssesment) 的组件中的页面查询。从 docs:

可以看出

Querying data with a Page Query

You can use the graphql tag to query data in the pages of your Gatsby site. This gives you access to anything included in Gatsby’s data layer, such as site metadata, source plugins, images, and more.

Querying data with the StaticQuery Component

StaticQuery is a component for retrieving data from Gatsby’s data layer in non-page components, such as a header, navigation, or any other child component.

也就是说,您在这里有两个选择。在顶级组件(页面)中使用查询并将 props 向下钻取到组件或使用 StaticQuery(或 useStaticQuery 挂钩)。