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

Gatsby 插件图像无法读取属性“startsWith”

如何解决Gatsby 插件图像无法读取属性“startsWith”

在网站上没有找到,但我确实找到了 open bug on Github,并且在撰写本文时唯一的解决方法是使用 GatsbyImage。学习将 Gatsby 项目从 2 转换为 3 我已经安装了 gatsby-plugin-image 并且正在转换在 Hero 组件中使用不变图像的组件,并且根据文档 StaticImage 应该可以工作。

旧组件:

import React from 'react'
import { graphql,useStaticQuery } from 'gatsby'
import Image from 'gatsby-image'


const query = graphql`
{
  person: file(relativePath: {eq: "person.png"}) {
    childImageSharp {
      fluid {
        ...GatsbyImageSharpFluid
      }
    }
  }
}
`

const Hero = ({ showPerson }) => {
  const { person } = useStaticQuery(query)

  return (
    <header className="hero">
      {showPerson && <Image fluid={person.childImageSharp.fluid} className="hero-person" />}
    </header>
  )
}

export default Hero

新组件:

import React from 'react'
import { StaticImage } from 'gatsby-plugin-image'

import personImage from '../assets/person.png'

const Hero = ({ showPerson }) => {
  console.log(personImage)
  return (
    <header className="hero">
      {showPerson && <StaticImage src={personImage} className="hero-person" alt="person image" />}
    </header>
  )
}

export default Hero

当我记录我得到的资产时(我的文件路径没有问题):

Hero.js:7 /static/person-c7035ca6b9544d80f8f0626ea3e22ace.png

但日志呈现:

react_devtools_backend.js:2430 No data found for image "undefined"
Image not loaded /static/person-c7035ca6b9544d80f8f0626ea3e22ace.png 

在终端中我得到:

"gatsby-plugin-image" threw an error while running the preprocessSource lifecycle:

Cannot read property 'startsWith' of undefined

对于 Gatsby 图像 StaticImage,是否有一种方法可以在不使用 GatsbyImage 的情况下呈现在组件中不会改变的图像?

解决方法

正如您从 docs about the new Gatsby Plugin Image 中看到的:

使用 StaticImage

的限制

图像在构建时加载和处理,所以有 将 props 传递给组件的方式的限制。价值观需要 在构建时进行静态分析,这意味着您无法通过 它们作为组件外部的道具,或使用结果 函数调用,例如。您可以使用静态值,或者 组件局部范围内的变量。请参阅以下内容 示例:

因此,<StaticImage> 组件无法处理 props 或函数调用来接收图像。在您的情况下,这应该有效:

import React from 'react'
import { StaticImage } from 'gatsby-plugin-image'

const Hero = ({ showPerson }) => {
  return (
    <header className="hero">
      {showPerson && <StaticImage src={`../assets/person.png`} className="hero-person" alt="person image" />}
    </header>
  )
}

export default Hero

由于您的 v2 方法的相似性,我建议使用 <GatsbyImage> 而不是 <StaticImage>,请检查它是否符合您的要求。

对于迁移问题,Gatsby has developed a codemod 处理所有 GraphQL 查询和“旧”gatsby-image,更改所需的查询和组件。安装插件后,只需运行:

npx gatsby-codemods gatsby-plugin-image

这样,问题应该就解决了。如果没有,您可以在以下位置跟踪类似的堆栈跟踪:

问题似乎与 3.2.0-next.0 版本有关,因此另一个选项是尝试降级(或升级,如果可能)。

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