Javascript 盖茨比:试图从前面的事物中获得图像路径,但是得到了这个;TypeError:无法读取属性';图像';“未定义”的定义;
我正在与盖茨比建立一个博客,我正在尝试在每个帖子页面上显示一个英雄形象,并在每个帖子的前面定义一个形象路径。但是,我从我的英雄组件中得到了这个错误:Javascript 盖茨比:试图从前面的事物中获得图像路径,但是得到了这个;TypeError:无法读取属性';图像';“未定义”的定义;,javascript,reactjs,graphql,gatsby,Javascript,Reactjs,Graphql,Gatsby,我正在与盖茨比建立一个博客,我正在尝试在每个帖子页面上显示一个英雄形象,并在每个帖子的前面定义一个形象路径。但是,我从我的英雄组件中得到了这个错误: TypeError:无法读取未定义的属性“image” 这是我的密码: 后前线事件 --- path: /blog-post1 title: Blog Post 1 image: ../../images/blog-post-1.jpg description: Blog post description --- Hero.js import R
TypeError:无法读取未定义的属性“image”
这是我的密码:
后前线事件
---
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
从“React”导入React
从“盖茨比图像”中导入Img;
康斯特英雄=道具=>(
有什么想法吗?提前谢谢。我假设您的frontmatter变量中始终有数据。如果您查看如何调用Hero组件,您将数据作为headerImage传递
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组件,您可以执行以下更改并进行检查
您可以将该条件添加到Img组件中,以避免由于缺少数据而导致的错误
<Hero headerImage={frontmatter.image} />
{
props.headerImage&&props.headerImage.image&&props.headerImage.image.childImageSharp
}
我发现了问题所在
在我的hero.js中,我使用{props.frontmatter.image.childImageSharp.resize}
但是在我的post.js中,我像这样将数据传递到hero组件
所以,它试图找到不存在的.image.image
,我所要做的就是删除.image
像这样
,所以,我尝试将其更改为您所拥有的,但我得到了一个不同的错误:类型错误:无法读取未定义的属性“childImageSharp”。这个问题可能是因为,最初您是这样做的没有数据。你能检查一下PostTemplate组件的渲染方法中frontmatter的值是多少吗。如果在任何时候你没有完整的数据,你会得到这个错误。好的,我知道了!因为我将frontmatter.image作为headerImage传递,所以我不需要说headerImage.image,因为这实际上意味着frontmatter.image.image,而h是错误的。所以,我所要做的就是删除.image。
{
props.headerImage && props.headerImage.image && props.headerImage.image.childImageSharp
<Img
fluid={props.headerImage.image.childImageSharp.resize}
/>
}