簡體   English   中英

Gatsby 插件圖像無法讀取屬性“startsWith”

[英]Gatsby plugin image cannot read property 'startsWith'

在網站上沒有找到這個,但我確實在 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的情況下渲染組件中不變的圖像?

正如您從有關新 Gatsby 插件圖像的文檔中看到的那樣:

使用StaticImage的限制

圖像在構建時加載和處理,因此對如何將 props 傳遞給組件有限制。 這些值需要在構建時進行靜態分析,這意味着您不能從組件外部將它們作為道具傳遞,或者使用 function 調用的結果,例如。 您可以使用 static 值或組件本地 scope 中的變量。 請參閱以下示例:

因此, <StaticImage>組件無法處理道具,也無法處理 function 調用來接收圖像。 在您的情況下,這應該有效:

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 開發了一個 codemod來處理所有 GraphQL 查詢和“舊” gatsby-image ,更改所需的查詢和組件。 安裝插件后,只需運行:

npx gatsby-codemods gatsby-plugin-image

有了這個,問題應該消失了。 如果沒有,您可以在以下位置跟蹤類似的堆棧跟蹤:

該問題似乎與3.2.0-next.0版本有關,因此另一種選擇是嘗試降級(或盡可能升級)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM