Gatsby项目project-details.js第7行报错求助:data未定义
问题解决:Gatsby 5.x 项目详情页data undefined报错
核心原因
你使用的是Gatsby 5.11,但NetNinja的教程基于Gatsby 2/3.x版本,这几个版本间存在API重大变更,导致模板无法正确获取GraphQL数据,同时旧的图片组件已被官方弃用,最终引发报错。
分步修复
1. 确认gatsby-node.js的页面创建配置
模板的data为undefined,大概率是页面创建时未将slug参数传递给模板的GraphQL查询。检查你的gatsby-node.js(无则新建),确保代码如下:
exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions // 查询所有项目的slug const projectQuery = await graphql(` query { allMarkdownRemark { nodes { frontmatter { slug } } } } `) // 为每个项目生成详情页 projectQuery.data.allMarkdownRemark.nodes.forEach(project => { createPage({ path: `/projects/${project.frontmatter.slug}`, component: require.resolve('./src/templates/project-details.js'), // 必须把slug传给模板,作为查询变量 context: { slug: project.frontmatter.slug, }, }) }) }
2. 替换弃用的gatsby-image组件
Gatsby 4+已废弃gatsby-image,改用gatsby-plugin-image,步骤如下:
安装依赖
npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-transformer-sharp
启用插件到gatsby-config.js
module.exports = { plugins: [ `gatsby-plugin-image`, `gatsby-plugin-sharp`, `gatsby-transformer-sharp`, // 保留你原本的其他插件(比如gatsby-source-filesystem等) ], }
修改project-details.js代码
- 替换图片组件导入:
// 删掉旧的 // import Img from "gatsby-image" // 导入新组件 import { GatsbyImage } from "gatsby-plugin-image"
- 修改GraphQL查询的图片字段:
把原查询中的...GatsbyImageSharpFluid替换为gatsbyImageData:
export const query = graphql` query ProjectDetails($slug: String) { markdownRemark(frontmatter: {slug: {eq: $slug}}) { html frontmatter { stack title featuredImg { childImageSharp { # 替换为新的图片数据查询 gatsbyImageData(layout: FULL_WIDTH) } } } } } `
- 替换组件中的图片渲染代码:
// 删掉旧的 // <Img fluid={featuredImg.childImageSharp.fluid} /> // 改成 <GatsbyImage image={featuredImg.childImageSharp.gatsbyImageData} alt={title} />
3. 添加可选链避免崩溃
为了防止data或嵌套字段为undefined时直接报错,修改组件中的变量解构:
const ProjectDetails = ({ data }) => { // 用可选链和默认值处理undefined情况 const markdownData = data?.markdownRemark || {} const { html } = markdownData const frontmatter = markdownData.frontmatter || {} const { title, stack, featuredImg } = frontmatter return ( <Layout> <div className={styles.details}> {/* 加判断避免空内容渲染 */} {title && <h2>{title}</h2>} {stack && <h3>{stack}</h3>} {featuredImg && ( <div className={styles.featured}> <GatsbyImage image={featuredImg.childImageSharp.gatsbyImageData} alt={title || 'Project image'} /> </div> )} {html && <div className={styles.html} dangerouslySetInnerHTML={{ __html: html }} />} </div> </Layout> ) }
4. 重启开发服务并清理缓存
执行以下命令确保缓存被清理,新配置生效:
gatsby clean && gatsby develop
验证修复
现在点击项目列表中的项目,应该能正常加载详情页,不会再出现data undefined的报错。
内容的提问来源于stack exchange,提问作者TARKUS
相关产品推荐
相关产品推荐

