【问题标题】:Can't load in images from Contentful using GatsbyJS无法使用 GatsbyJS 从 Contentful 加载图像
【发布时间】:2020-05-20 23:18:46
【问题描述】:

第一次在这里发帖,但我已经为此苦苦挣扎了几天。

基本上,我有一个 graphQL 查询,它从内容中提取产品数据,然后将其显示在 GatsbyJS 页面上。查询正确显示产品的标题、价格和描述,但不会加载到图像中。不幸的是,我不断收到错误消息,例如:

“TypeError: 无法读取未定义的属性‘0’”

无法读取未定义的属性“src”。 (将查询更改为查看图像的 src 时。当我执行此方法时,根据 GraphiQL,url 确实有一个值)

这是我目前正在处理的页面的代码:

import React from 'react'
import { graphql } from 'gatsby'
import Img from 'gatsby-image'

import Layout from '../components/Layout'
import './shop.scss'

const Shop = ({ data }) => {

    return (
        <Layout>
            <section>
              {data.allContentfulProducts.edges.map( ({ node }) => (
                <article key={node.id}>
                  <Img
                    fluid={node.images.fluid}
                  />
                  <p>{node.productName}</p>
                </article>
              ))}
            </section>
        </Layout>
    )
}

export const productQuery = graphql`
  query {
    allContentfulProducts {
      edges {
        node {
          id
          productName
          images {
            fluid {
              ...GatsbyContentfulFluid
            }
          }
        }
      }
    }
  }
`

export default Shop

【问题讨论】:

  • 您是在内容中添加单个图像到产品中,还是添加多个图像?如果它是多个,则表明 images 是一个数组,您需要在访问它们的每个 fluid 属性之前映射 node.images
  • 提供样本数据 - images 零件 - 为所有产品定义的图像?
  • 非常感谢。哦,我觉得很愚蠢。由于某种原因,我没有想到我在内容模型中的图像字段是一个数组。我通过添加 node.images[0].fluid 来修复它。

标签: reactjs graphql gatsby contentful gatsby-image


【解决方案1】:

我认为您的 graphQL 查询有问题。试试这个:

export const productQuery = graphql`
  query {
    allContentfulProducts {
      edges {
        node {
          id
          productName
          image {
            fluid {
              src
              ...GatsbyContentfulFluid
            }
          }
        }
      }
    }
  }
`

如果此查询没有帮助,请向我们展示您的内容资产的结构。

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2018-05-28
    • 2018-07-08
    • 2019-08-20
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2015-07-25
    • 2018-04-05
    相关资源
    最近更新 更多