Gatsby结合Contentful+GraphQL加载图片时报Cannot read property错误如何解决?
问题定位
- 数组访问错误:返回的
allContentfulHeroImage.edges是数组类型,你的代码中直接写edges.node是尝试访问数组对象本身的node属性,该属性不存在所以返回undefined,进而触发Cannot read property 'heroImage' of undefined报错。 - API不兼容问题:你当前使用的
fluid语法是已废弃的gatsby-image的专用API,和你引入的gatsby-plugin-image不匹配,同时组件导入方式也不符合新插件的要求。
解决方案
方案1:完全适配gatsby-plugin-image(官方推荐)
第一步:替换GraphQL查询为新插件专用语法
query MyQuery { allContentfulHeroImage { edges { node { heroImage { gatsbyImageData(maxWidth: 2000, layout: FULL_WIDTH) } } } } }
第二步:修正组件导入和渲染逻辑
import * as React from "react" import { graphql } from "gatsby" import { GatsbyImage, getImage } from "gatsby-plugin-image" import Layout from "../components/layout" import Seo from "../components/seo" import Navbar from "../components/Navbar" function App( {data} ) { // 取edges数组第一个元素的node数据,有多条需求时可以遍历edges数组 const heroImage = getImage(data.allContentfulHeroImage.edges[0].node.heroImage) return ( <> <Layout> <GatsbyImage image={heroImage} alt="自定义替换alt文本" /> </Layout> </> ) } export default App;
方案2:保留旧fluid语法
如果暂时不想调整查询逻辑,可以回退使用废弃的gatsby-image包:
- 执行
npm install gatsby-image安装旧包 - 将导入语句改为
import Img from 'gatsby-image' - 渲染部分修正数组访问即可:
<Img fluid={data.allContentfulHeroImage.edges[0].node.heroImage.fluid} />
内容的提问来源于stack exchange,提问作者jibreal
相关产品推荐
相关产品推荐

