【发布时间】: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