我正在尝试查询文件夹中的所有图像,并使用tailwindCSS和gatsby-image在卡网格中显示它们。我已经能够查询和显示一个图像,但是当我尝试使用一个图像文件夹进行操作时,即使查询在GraphQL资源管理器中有效,也会出现错误“ TypeError:无法读取未定义的属性'edges'” 。我已经阅读了文档,看了其他教程,并尝试了许多不同的方式,但无法找出问题所在。任何帮助是极大的赞赏!
import React from "react";
import { graphql } from "gatsby";
import Img from "gatsby-image";
import Layout from "../components/layout";
import SEO from "../components/seo";
const ArtPage = props => (
<Layout>
<SEO
keywords={[`art`, `paint`, `draw`]}
title="Art"
/>
<div class="flex flex-wrap mt-2 mx-1">
{props.artImages.edges.map(img => (
<div class="w-full md:w-1/2 lg:w-1/2 px-2 my-2">
<div className="rounded overflow-hidden shadow-lg">
<Img
className="w-full"
fluid={img.node.childImageSharp.fluid}
/>
</div>
</div>
))}
</div>
</Layout>
)
export default ArtPage;
export const query = graphql`
query artImages {
allFile(filter: { relativePath: { regex: "/art/.*.png/" } } )
{
edges {
node {
relativePath
name
childImageSharp {
fluid(maxWidth: 500) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`;
答案 0 :(得分:1)
调试此类问题始终很困难。由于您说您的查询在GraphiQL中是正确的,因此您可能在引用GraphQL树中的正确属性时犯了一个错误。 undefined
是指示您引用了不存在的对象的指示符。
用于调试此问题的秘密武器实际上是console.log(graphQlobject)
。在浏览器中打印对象,然后尝试访问属性,直到正确为止。
我将为您提供我在项目中使用的HeaderSupplier组件,并用注释引用重要的内容:
import React from "react";
import { graphql, useStaticQuery } from "gatsby";
import GatsbyImage from "gatsby-image";
import styled from "styled-components";
import { pickRandomly } from "../util/utilityFunctions";
/**
* Returns one random image header.
* Uses GatsbyImage and GraphQL to load images.
* @see https://www.orangejellyfish.com/blog/a-comprehensive-guide-to-images-in-gatsby/
*/
const HeaderSupplier = () => {
const { allFile } = useStaticQuery(graphql`
query {
allFile(filter: {
extension: {regex: "/(jpg)|(jpeg)|(png)/"},
sourceInstanceName: {eq: "headers"}})
// filter by sourceInstanceName, see the gatsby-config.js,
// this way you get exactly the files you need without complicated regex statements
{
edges {
node {
childImageSharp {
fluid(maxWidth: 150, quality: 100) {
originalName
...GatsbyImageSharpFluid
}
}
}
}
}
}`);
// use console.log for debugging and correctly navigating the graphQL tree
console.log(allFile);
const header = pickRandomly(allFile.edges);
const { fluid } = header.node.childImageSharp;
// make sure you reference the correct objects
// if you get undefined you made a mistake navigating the GraphQL tree
return (
<GatsbyImage fluid={fluid} alt={fluid.originalName} />
);
};
export default HeaderSupplier;
gatsby-config.js
中的源实例:
{
resolve: "gatsby-source-filesystem",
options: {
path: `${__dirname}/src/components/library/headers`,
name: "headers",
},
答案 1 :(得分:0)
我使用的是props.artImages而不是props.data.artImages哦