TypeError: Cannot read property 'image' of undefined - React & Gatsby

TypeError: Cannot read property 'image' of undefined - React & Gatsby

我目前正在尝试从我的 React 应用程序中的 Contentful 中提取一些数据,并不断收到此类型错误:无法读取未定义的 属性 'image'。

我似乎不明白为什么会这样。

这是我的查询组件 - 只是试图拉入文件名:

import React from 'react'
import { StaticQuery, graphql } from 'gatsby'

export default () => (
  <StaticQuery
    query={graphql`
      query FileQuery {
        allContentfulImage {
          edges {
            node {
              image {
                file {
                  fileName
                }
              }
            }
          }
        }
      }
    `}
    render={data => (
      <div>
        <h1>{data.allContentfulImage.edges.node.image.file.fileName}</h1>
      </div>
    )}
  />
)

data.allContentfulImage.edges 包含一个对象数组而不是一个对象。你可以试试:

<h1>{data.allContentfulImage.edges[0].node.image.file.fileName}</h1>