什么是 gatsbyContentfulFluid?

What is gatsbyContentfulFluid?

我作为新手正在学习 Gatsby 和 GraphQL 并关注这篇文章 https://ibaslogic.com/gatsby-with-contentful-cms/

它有这个代码:

export const query = graphql`
  query($slug: String!) {
    contentfulBlogPost(slug: { eq: $slug }) {
      title
      publishedDate(formatString: "Do MMMM, YYYY")
      featuredImage {
        fluid(maxWidth: 750) {
          ...GatsbyContentfulFluid
        }
      }
    }
  }
`

我得到了所有东西,但在我的 GraphQL 查询服务器上没有得到 ...GatsbyContentfulFluid。 C 有人请解释一下 ...GatsbyContentfulFluid 是什么? 为什么我们将它与传播运算符一起使用? 我在创建内容丰富的数据时是否遗漏了什么,这就是为什么我在我的 GQL 查询游乐场中没有得到 ...GatsbyContentfulFluid 的原因?

它不是我们在 JavaScript 中所知道的展开运算符,在 GraphQL 中代表查询片段。

片段是一种使用可重用单元查询一组字段的方法。来自 GraphQL docs:

Let's say we had a relatively complicated page in our app, which lets us look at two heroes side by side, along with their friends. You can imagine that such a query could quickly get complicated, because we would need to repeat the fields at least once - one for each side of the comparison.

That's why GraphQL includes reusable units called fragments. Fragments let you construct sets of fields, and then include them in queries where you need to. Here's an example of how you could solve the above situation using fragments:

在您的情况下,片段由 gatsby-source-contentful and basically, is querying a fluid asset from Contentful, as you do normally when using gatsby-image 为本地文件提供。

换句话说,使用 ...GatsbyContentfulFluid 片段,您可以从 Contentful 资产中获取必填字段,这些字段允许您在资产中使用 gatsby-image

由于 GraphiQL 的限制,片段在 GraphQL playground 中不可用:

Note, due to a limitation of GraphiQL, you can not currently use these fragments in the GraphiQL IDE.

因此,您可以使用片段(实际上,您应该),但您需要直接在代码中检查获取的数据(通过 console.logs 或通过调试断点),因为它们在 GraphQL 中不可用游乐场。