问题描述
我即将退出(再次!!)但要坚持下去..
非常感谢这方面的帮助,否则我的笔记本电脑可能很快就会被扔出窗外!
我在本地建立了一个项目,现在将其链接到 Strapi 上的内容。我可以很好地添加来自 Strapi 的文本数据,但我真正在苦苦挣扎的是 GatsbyImage 数据。
我收到此错误:
警告:道具类型失败:道具 image
在 GatsbyImage
中被标记为必需,但其值为 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'
或者它可能是 .map 函数中的 getimage() 吗? - const pathToImage = getimage(image);
如果有人能帮助我,我将不胜感激,我已经坚持了很多年了!
解决方法
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" /
>
);
})
})