微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Gatsby 中,如何将相对路径文件传递给也正在拉查询的模板?

如何解决在 Gatsby 中,如何将相对路径文件传递给也正在拉查询的模板?

在 Gatsby 中,我编写了一个单独的帖子模板:

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文件的前面有一个特征图:

---
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 文件没有图像,我会收到以下错误

无法读取 null 的属性 'childImageSharp'

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

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
    }
  }
`)

我收到以下错误

如果您使用的不是页面查询而是 useStaticQuery / StaticQuery 您看到此错误是因为它们目前不支持变量。

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

解决方法

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

在 Gatsby 中,我如何查询 slug 并通过默认值 图像到特征图像组件?

在使用页面查询时,您可以使用附加 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 添加为可空值(通过删除感叹号 !),因为正如您所说,并非所有帖子都会有它。

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。