【问题标题】:GatsbyImage working when pulling data locally but not with Strapi and GatsbyGatsbyImage 在本地提取数据时工作,但不使用 Strapi 和 Gatsby
【发布时间】:2021-08-11 21:15:26
【问题描述】:

我正处于退出的边缘(再次!!)但坚持下去..

非常感谢您对此的帮助,否则我的笔记本电脑可能很快就会被扔出窗外!

我在本地设置了一个项目,现在将其链接到 Strapi 上的内容。我可以很好地从 Strapi 添加文本数据,但我真正苦苦挣扎的是 GatsbyImage 数据。

我收到此错误:

警告:失败的道具类型:道具imageGatsbyImage中标记为必填,但其值为undefined

这是我的代码:

import React from "react";
import { SubTitle } from "../components/styles/Styles";
import { GatsbyImage, getImage } from "gatsby-plugin-image";
import { graphql, useStaticQuery } from "gatsby";
import { ImageLayout } from "../components/styles/GridLayout";

// featured products on home page

const query = graphql`
  {
    allStrapiNewArrivals {
      nodes {
        images {
          localFile {
            childImageSharp {
              gatsbyImageData(
                placeholder: BLURRED
                layout: CONSTRAINED
                height: 400
                width: 400
              )
            }
          }
        }
      }
    }
  }
`;

const FeatureProducts = () => {
  const data = useStaticQuery(query);
  const nodes = data.allStrapiNewArrivals.nodes;
  console.log(nodes);
  return (
    <div>
      <SubTitle>New Arrivals</SubTitle>
      <ImageLayout>
        <div>
          <div className="collection-cards">
            {nodes.map((image, index) => {
              const pathToImage = getImage(image);
              return (
                <GatsbyImage
                  image={pathToImage}
                  alt=""
                  key={index}
                  className="collection"
                />
              );
            })}
          </div>
        </div>
      </ImageLayout>
    </div>
  );
};

export default FeatureProducts;

当我 console.log(nodes) 返回时:

[{…}]
0:
images: Array(3)
0: {localFile: {…}}
1: {localFile: {…}}
2: {localFile: {…}}
length: 3
__proto__: Array(0)
__proto__: Object
length: 1
__proto__: Array(0)

我的想法 - 在 allStrapiNewArrivals 数据中,'images{ localFile' 位可能是原因吗?因为在本地提取数据时没有列出这些。例如。它应该是:'file{childImageSharp'

我尝试使用 'const nodes = data.allStrapiNewArrivals.nodes.images.localFile' 但这也会引发以下错误:

无法读取未定义的属性“地图”

或者它可以是 .map 函数中的 getImage() 吗? - const pathToImage = getImage(image);

如果有人可以提供帮助,我将不胜感激,我已经坚持了很久!

【问题讨论】:

    标签: undefined gatsby gatsby-image gatsby-plugin


    【解决方案1】:

    images 是一个图像数组,因此您也必须对其进行映射。也可以试试gatsby clean

    nodes.map((node, index) => {
      return node.images.map(image => {
        const pathToImage = getImage(image.localFile);
        return ( <
          GatsbyImage image = {
            pathToImage
          }
          alt = ""
          key = {
            index
          }
          className = "collection" /
          >
        );
      })
    })

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 2019-12-05
      • 2016-10-09
      • 1970-01-01
      • 2021-08-14
      • 2022-07-12
      • 1970-01-01
      • 2021-06-15
      • 2020-11-26
      相关资源
      最近更新 更多