首页 > 解决方案 > 盖茨比:试图从前端获取图像路径但得到这个“类型错误:无法读取未定义的属性'图像'”

问题描述

我正在用 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
            }
          }
        }
      }
    }
  }
`;

关于发生了什么的任何想法?提前致谢。

标签: javascriptreactjsgraphqlgatsby

解决方案


我假设您一直在 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}
    />
}

推荐阅读