【问题标题】:how to show media content from contentful using gatsby如何使用 gatsby 从内容中显示媒体内容
【发布时间】:2020-04-29 01:34:30
【问题描述】:

通过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

如何嵌入该图像?

【问题讨论】:

  • 尝试在.map 函数中插入console.log(edge)。边缘对象是什么样的?如果未定义,请在返回 Layout 之前尝试 console.log(data)。您是否像在 graphQL 游乐场中一样获取数据?
  • 我认为错误的发生是因为并非所有人都有 heroImage。所以我这样做了: {console.log( edge.node.heroImage.file ? "has hero image" : "has no hero image")} 但这也破坏了它。我得到'TypeError:无法读取属性'file'为空'

标签: graphql media gatsby contentful


【解决方案1】:

我认为它引发了错误,因为并非所有内容丰富的帖子都有 heroImage。我添加了一个三元来查看 {edge.node.heroImage.file.url} 是否存在,但是,我认为这也引发了错误,因为某些帖子不存在 edge.node.heroImage。所以,这是有效的:

{edge.node.heroImage && (
    <img
         src={edge.node.heroImage.file.url}
         alt={edge.node.title}
    />
)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多