问题描述
我正在与 Sanity 和 Gatsby 合作
我正在尝试映射一组图像以在图像库中显示它们。我的 GraphQL 查询正在运行,我可以显示单个图像,但收到错误:TypeError: Cannot read property 'fluid' of null
当我尝试映射数组时。
非常感谢任何方向!
我的查询:
{
sanitygallery {
images {
asset {
fluid {
...GatsbySanityImageFluid
}
}
}
}
}
这个作品:
const images = data.sanitygallery.images
<Img className="grow" fluid={images[0].asset.fluid} />
这不会:
const images = data.sanitygallery.images
<div className="img-container">
{images.map((image,index) => {
console.log(image.asset.fluid); // <-- when adding this it logs the info in the screenshot below
return (
<div className="Box">
<Img className="grow" fluid={image.asset.fluid} key={index} />
</div>
)
})}
</div>
解决方法
尝试类似:
const images = data.sanityGallery.images
<div className="img-container">
{images.map((image,index) => {
console.log(image.asset); //
return (
<div className="box">
{image.asset && <Img className="grow" fluid={image.asset.srcSet} key={index} />}
</div>
)
})}
</div>