如何使用盖茨比显示内容满意的媒体内容

问题描述 投票:1回答:1

通过Andrew Mead's gatsby tutorial。我建立了一个令人满意的模型,并在其中设置了用于英雄形象的媒体字段。富文本和文本字段可以正常工作。在索引页面中,我希望每个帖子都显示英雄图像的缩略图。我的graphql查询如下所示,您可以在其中看到heroImage,它在graphql游乐场中可以正常工作:

  const data = useStaticQuery(graphql`
    query {
      allContentfulWork(sort: { fields: publishedDate, order: DESC }) {
        edges {
          node {
            title
            slug
            publishedDate(formatString: "MMMM Do, YYYY")
            heroImage {
              file {
                url
              }
            }
          }
        }
      }
    }
  `)

^^这在graphql游乐场中有效。在下面的index.js中,我要返回:

return (
    <Layout>
      <ul className={workStyles.indexPage}>
        {data.allContentfulWork.edges.map(edge => {
          return (
            <li>
              <Link to={`/work/${edge.node.slug}`}>
                <h3>{edge.node.title}</h3>
                {edge.node.publishedDate}
                <img src={edge.node.heroImage.file.url} />
              </Link>
            </li>
          )
        })}
      </ul>
    </Layout>
  )

问题是{edge.node.heroImage.file.url}返回错误TypeError: Cannot read property 'file' of null

如何嵌入该图像?

graphql media gatsby contentful
1个回答
0
投票

我认为这会引发错误,因为并非所有有争议的帖子都具有heroImage。我添加了一个三进制,以查看是否存在{edge.node.heroImage.file.url},但是,我认为这也引发了错误,因为某些帖子不存在edge.node.heroImage。因此,这是有效的方法:

{edge.node.heroImage && (
    <img
         src={edge.node.heroImage.file.url}
         alt={edge.node.title}
    />
)}
© www.soinside.com 2019 - 2024. All rights reserved.