如何使用GatsbyJS和GraphQL查询和显示包含多个图像的文件夹



我正在尝试查询文件夹中的所有图像,并将它们显示在带有tailwindCSS和gatsby图像的卡片网格中。我已经能够查询和显示一个图像,但当我尝试使用图像文件夹时,我会收到错误"TypeError:无法读取未定义的属性‘edges’",即使查询在GraphQL资源管理器中有效。我读过文档,看过其他教程,现在尝试了很多不同的方法,但都不知道出了什么问题。非常感谢您的帮助!

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
}
}
}
}
} 
}
`;

调试这样的问题总是很困难的。由于您在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",
},

我使用的是props.artImages而不是props.data.artImages ooooooo ps

最新更新