在 Gatsby 中,我如何将相对路径文件传递给同样拉取查询的模板?

In Gatsby how do I pass a relative path file to a template that is also pulling a query?

在 Gatsby 中,我编写了一个 post 模板:

singlePost.js:

import React from 'react'
import { graphql } from 'gatsby'
import { MDXRenderer } from 'gatsby-plugin-mdx'
import { H1 } from '../elements'
import { Container, Post, FeatureImage } from '../components'
const singlePost = ({ data }) => {
  const featureImage = data.mdx.frontmatter.featureImg.childImageSharp.fixed
  return (
    <Container>
      <FeatureImage fixed={featureImage} />
      <Post>
        <H1 margin=" 0 0 2rem 0">{data.mdx.frontmatter.title}</H1>
        <MDXRenderer>{data.mdx.body}</MDXRenderer>
      </Post>
    </Container>
  )
}
export const pageQuery = graphql`
  query SinglePostQuery($id: String!) {
    mdx(id: { eq: $id }) {
      body
      frontmatter {
        date
        excerpt
        featureImg {
          childImageSharp {
            fixed(width: 1920) {
              ...GatsbyImageSharpFixed
            }
          }
        }
        title
        slug
      }
    }
  }
`
export default singlePost

在我的 gatsby-node.js 中,我从 slug 获取数据:

 data.allMdx.edges.map(edge => {
    const slug = edge.node.frontmatter.slug
    const id = edge.node.id
    actions.createPage({
      path: slug,
      component: require.resolve(`./src/templates/singlePost.js`),
      context: { id },
    })
  })

在markdown文件的frontmatter中有一张特色图片:

---
title: Bacon Ipsum
slug: bacon
date: 2021-02-09
featureImg: nature.jpg
excerpt: Bacon ipsum dolor amet pastrami prosciutto meatball fatback, andouille drumstick shank burgdoggen brisket cow turkey.
---

如果 post markdown 文件没有图像,我会得到一个错误:

Cannot read property 'childImageSharp' of null

我可以访问我设置的默认图像:

const defaultImage = useStaticQuery(graphql`
  query {
    default: file(relativePath: { eq: "default.jpg" }) {
      publicURL
    }
  }
`)

但是当我尝试查询内容和默认值时:

const defaultImage = useStaticQuery(graphql`
  query SinglePostQuery($id: String!) {
    mdx(id: { eq: $id }) {
      body
      frontmatter {
        date
        excerpt
        featureImg {
          childImageSharp {
            fixed(width: 1920) {
              ...GatsbyImageSharpFixed
            }
          }
        }
        title
        slug
      }
    }
    default: file(relativePath: { eq: "default.jpg" }) {
      publicURL
    }
  }
`)

我收到以下错误:

If you're not using a page query but a useStaticQuery / StaticQuery you see this error because they currently don't support variables.

在 Gatsby 中,如何查询 slug 并将默认图像传递给特征图像组件?

根据错误日志指出,useStaticQuery(因为它是一种静态查询)不接受变量,因此得名。

In Gatsby how can I query the slug but also have pass the default image to the Feature Image component?

在使用页面查询时,您可以使用附加 id 的相同上下文来传递图像。

  data.allMdx.edges.map(edge => {
        const slug = edge.node.frontmatter.slug
        const id = edge.node.id
        const imagePath = edge.node.featureImg || 'default.jpg'
        actions.createPage({
          path: slug,
          component: require.resolve(`./src/templates/singlePost.js`),
          context: { 
            id 
            imagePath
           },
        })
      })

注意:您可能需要查询gatsby-node.js中的图片。如果需要,将 imagePath 更改为与您的数据结构更匹配的另一个标识符。

然后,在您的模板中:

import React from 'react'
import { graphql } from 'gatsby'
import { MDXRenderer } from 'gatsby-plugin-mdx'
import { H1 } from '../elements'
import { Container, Post, FeatureImage } from '../components'
const singlePost = ({ data }) => {
  const featureImage = data.mdx.frontmatter.featureImg.childImageSharp.fixed
  return (
    <Container>
      <FeatureImage fixed={featureImage} />
      <Post>
        <H1 margin=" 0 0 2rem 0">{data.mdx.frontmatter.title}</H1>
        <MDXRenderer>{data.mdx.body}</MDXRenderer>
      </Post>
    </Container>
  )
}
export const pageQuery = graphql`
  query SinglePostQuery($id: String!, $imagePath: String) {
    mdx(id: { eq: $id }) {
      body
      frontmatter {
        date
        excerpt
        featureImg {
          childImageSharp {
            fixed(width: 1920) {
              ...GatsbyImageSharpFixed
            }
          }
        }
        title
        slug
      }
    }
    default: file(relativePath: { eq: $imagePath }) {
      publicURL
    }
  }
`
export default singlePost

注意:将 $imagePath 添加为可为 null 的值(通过删除感叹号 !),因为正如您所说,并非所有帖子都会有它.

如果 featureImg 块仍然破坏查询,请尝试删除它。因为:

const imagePath = edge.node.featureImg || 'default.jpg'

您的 imagePath 变量将始终包含所需的数据,或者您的 featureImg,或者您的默认数据。关键是要单独查询。