javascript - 盖茨比:试图从前端获取图像路径但得到这个“类型错误:无法读取未定义的属性'图像'”
问题描述
我正在用 Gatsby 构建一个博客,并且我试图在每个帖子页面上显示一个英雄图像,其中的图像路径在每个帖子的前面问题中定义。但是,我从我的英雄组件中收到了这个错误:
TypeError: Cannot read property 'image' of undefined
这是我的代码:
帖子前端问题
---
path: /blog-post1
title: Blog Post 1
image: ../../images/blog-post-1.jpg
description: Blog post description
---
Hero.js
import React from 'react'
import Img from "gatsby-image";
const Hero = props => (
<section className="hero is-large">
<Img
fluid={props.frontmatter.image.childImageSharp.resize}
/>
<div className="hero-body">
</div>
</section>
);
export default Hero
Post.js
import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/layout';
import Hero from '../components/hero';
const PostTemplate = ({ data }) => {
const { markdownRemark } = data;
const { frontmatter, html } = markdownRemark;
return (
<Layout>
<Hero headerImage={frontmatter.image} />
<section class="section">
<div className="container is-medium">
<div dangerouslySetInnerHTML={{__html: html}} />
</div>
</section>
</Layout>
)
}
export default PostTemplate;
export const pageQuery = graphql`
query($path: String!) {
markdownRemark(frontmatter: { path: { eq: $path } }) {
html
frontmatter {
date
path
title
description
image {
childImageSharp {
resize(width: 1500, height: 1500) {
src
}
fluid(maxWidth: 786) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`;
关于发生了什么的任何想法?提前致谢。
解决方案
我假设您一直在 frontmatter 变量中有数据。如果您查看如何调用 Hero 组件,您将在其中将数据作为 headerImage 传递。
<Hero headerImage={frontmatter.image} />
如果您查看 Hero 组件,您正在阅读它作为frontmatter,您可以进行以下更改并检查。
您可以将条件添加到 Img 组件以避免由于缺少数据而导致的错误。
{
props.headerImage && props.headerImage.image && props.headerImage.image.childImageSharp
<Img
fluid={props.headerImage.image.childImageSharp.resize}
/>
}
推荐阅读
- java - 使用 Jackson 数据绑定将对象序列化为 Map 而不是 String?
- vba - AHK中的COM来操作Word。Documents.Activate 不可预知的行为
- mysql - MySQL 中的存储函数不起作用(无效使用 groupby)
- wpf - 我可以在具有目标框架 4.0 的应用程序中使用针对 .net 框架 v3.5 的 .dll 库吗?
- python - 通过另一个数据框的行名选择数据框的列
- linux - 如何诊断为什么找不到共享库?
- java - 如何使用 Swing 制作一个 GUI,从列表中选择两个元素并向用户显示两个按钮,以便他们选择获胜者?
- excel - VBA:比较两个单元格(它们可能包含空格)
- .net - 由于域不受信任,SQL 登录失败
- reactjs - onChange() 触发两次,使复选框无法更改(反应应用程序)