Gatsby加载Contentful About页报allContentfulAbout未定义错误
问题描述
使用Gatsby对接Contentful开发站点时,加载About页面抛出图片加载错误,控制台提示:
data.allContentfulAbout is undefined
已完成的前置验证:
- 本地
localhost:8000的GraphQL调试面板中,对应查询语句可正常返回bioImage、aboutText字段数据 - 项目内Blog页面通过
useStaticQuery查询Contentful博客列表数据运行正常 - 修复目标:实现Contentful图片、
aboutText字段raw文本内容的正常渲染
问题根因
代码存在三处核心错误:
- 静态查询缺少
useStaticQuery钩子包裹:Gatsby组件内调用静态查询必须通过useStaticQuery包裹graphql模板字符串,直接将graphql模板赋值给变量,拿到的只是查询语法树对象,不是接口返回的实际数据,这是data下找不到对应字段的核心原因,和正常运行的Blog页代码对比可直接发现该差异。 - 数据取值路径错误:
allContentfulAbout接口返回的内容集合存放在nodes数组字段下,代码中直接访问不存在的data.allContentfulAbout.node属性,会触发属性不存在的报错。 - 缺少Contentful富文本渲染逻辑:
aboutText.raw是富文本JSON结构,不能直接作为文本插入DOM,需要用官方渲染方法解析。
修复步骤
- 先安装Contentful富文本渲染依赖,在项目根目录执行命令:
npm install @contentful/rich-text-react-renderer
- 替换About页面原有代码为修正后的版本:
import React from "react"; import { Link, graphql, useStaticQuery } from "gatsby"; import SEO from '../components/seo' import { GatsbyImage, getImage } from "gatsby-plugin-image"; import Layout from "../components/layout"; import Head from '../components/head' import { renderRichText } from "@contentful/rich-text-react-renderer"; import * as aboutStyles from '../styles/about.module.scss' const AboutPage = () => { const data = useStaticQuery(graphql` query { allContentfulAbout { nodes { bioImage { title gatsbyImageData( cropFocus: CENTER resizingBehavior: SCALE width: 500 placeholder: BLURRED layout: FULL_WIDTH ) } aboutText { raw } } } } `) // About为单条内容,取nodes数组第一项即可 const aboutContent = data.allContentfulAbout.nodes[0] const bioImage = getImage(aboutContent.bioImage) return ( <div> <Layout> <SEO title="About" /> <Head title="About" /> <div className={aboutStyles.parent}> <section className={aboutStyles.container}> <div className={aboutStyles.image}> <GatsbyImage image={bioImage} alt={aboutContent.bioImage.title}/> </div> <div className={aboutStyles.info}> {renderRichText(aboutContent.aboutText)} </div> </section> </div> </Layout> </div> ) } export default AboutPage
关键修改说明
- 从
gatsby依赖中导入useStaticQuery钩子,用它包裹GraphQL查询语句,和Blog页查询写法保持一致,确保能拿到实际返回的查询数据 - 修正数据取值路径,从
allContentfulAbout.nodes数组中读取About页面配置内容,避免访问不存在的node属性 - 提前通过
getImage方法处理图片数据,简化模板内代码的同时兼容空值场景 - 引入
renderRichText方法解析aboutText的raw富文本内容,直接渲染为结构化的DOM元素
内容的提问来源于stack exchange,提问作者kenton
相关产品推荐
相关产品推荐

