首页 > 解决方案 > ...GatsbySanityImageFluid - 无法读取 null 的属性“流体”

问题描述

我正在与理智和盖茨比合作

我正在尝试映射一组图像以在图像库中显示它们。我的 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>

在此处输入图像描述

标签: graphqlgatsbysanity

解决方案


尝试类似:

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>

推荐阅读