盖茨比插件图像无法读取属性'startsWith'



我在网站上没有发现这个,但我确实在Github上发现了一个打开的bug,在撰写本文时,唯一的解决方案是使用GatsbyImage。学习将Gatsby项目从2转换为3我已经安装了Gatsby插件映像,并且正在转换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的情况下渲染组件中不变的图像?

您可以从有关新Gatsby插件图像的文档中看到:

使用StaticImage的限制

图像是在构建时加载和处理的,因此对如何将道具传递到组件的限制。价值观需要在构建时进行静态分析,这意味着您不能通过它们作为组件外部的道具,或者使用例如,函数调用。您可以使用静态值,或者组件本地范围内的变量。请参见以下内容示例:

因此,<StaticImage>组件既不能处理道具,也不能处理接收图像的函数调用。在您的情况下,这应该有效:

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开发了一个处理所有GraphQL查询的codemod;旧的";gatsby-images,更改所需的查询和组件。一旦你安装了插件,只需运行:

npx gatsby-codemods gatsby-plugin-image

这样一来,这个问题就应该消失了。如果没有,您可以在以下位置遵循类似的堆栈跟踪:

  • https://github.com/gatsbyjs/gatsby/issues/30143

  • https://github.com/gatsbyjs/gatsby/issues/30030

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

最新更新