getImage返回undefined,所以我的GatsbyImage组件不被渲染。
文件结构:
- src/页面/gallery.js
- src/images(有12张照片命名为photo-01.jpg, photo-02.jpg,…)
我有以下代码(gallery.js):
import React from "react";
import Layout from "../components/Layout";
import { useStaticQuery, graphql } from "gatsby";
import { GatsbyImage, getImage } from "gatsby-plugin-image";
const Gallery = () => {
const { gallery } = useStaticQuery(graphql`
query {
gallery: allFile(
filter: {
extension: { eq: "jpg" }
absolutePath: { regex: "/images/" }
}
) {
nodes {
id
childImageSharp {
fluid(maxWidth: 500, maxHeight: 500) {
...GatsbyImageSharpFluid_tracedSVG
}
}
}
}
}
`);
return (
<Layout>
<div className="container py-5">
<div className="row">
<div className="col-12">
<h1 className="text-gastby mb-4">Gallery</h1>
</div>
</div>
<div className="row">
{gallery.nodes.map((image) => (
<div className="col-lg-3 col-md-4 col-sm-6 mb-3" key={image.id}>
<GatsbyImage
image={getImage(image.childImageSharp.fluid)}
alt="Gallery"
/>
</div>
))}
</div>
</div>
</Layout>
);
};
export default Gallery;
我有什么错吗?
问题是您正在混合gatsby-image
(从盖茨比1到盖茨比2)和gatsby-plugin-image
(从盖茨比3开始)。第一个现在已弃用。
当你查询fluid
或fixed
GraphQL节点时,这可以很容易地发现,因为它们是由gatsby-image
创建的,它使用Img
(from 'gatsby-image
')组件,它接受fluid
或fixed
属性。
另一方面,gatsby-plugin-image
查询gatsbyImageData
(不是fluid
或fixed
)和相应的GatsbyImage
(from 'gatsby-plugin-image'
)组件接受image
属性。
在您的情况下,您正在查询应用于gatsby-plugin-image
组件的gatsby-image
结构,这就是为什么它返回undefined
。
检查迁移指南,但实际上您需要替换(并删除)所有对gatsby-image
的引用,并安装所需的依赖项:
npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-transformer-sharp
添加到你的gatsby-config.js
:
module.exports = {
plugins: [
`gatsby-plugin-image`,
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
],
}
并将您的查询更改为:
const Gallery = () => {
const { gallery } = useStaticQuery(graphql`
query {
gallery: allFile(
filter: {
extension: { eq: "jpg" }
absolutePath: { regex: "/images/" }
}
) {
nodes {
id
childImageSharp {
gatsbyImageData(layout: FIXED)
}
}
}
}
`);
return (
<Layout>
<div className="container py-5">
<div className="row">
<div className="col-12">
<h1 className="text-gastby mb-4">Gallery</h1>
</div>
</div>
<div className="row">
{gallery.nodes.map((image) => (
<div className="col-lg-3 col-md-4 col-sm-6 mb-3" key={image.id}>
<GatsbyImage
image={getImage(image.childImageSharp)}
alt="Gallery"
/>
</div>
))}
</div>
</div>
</Layout>
);
};
export default Gallery;
请仔细检查查询,因为应用gatsby-plugin-image
时节点和结构可能不同。
注意getImage
是一个辅助函数,您可能不需要它,可以考虑直接使用:
<GatsbyImage
image={image.childImageSharp.gatsbyImageData}
alt="Gallery"
/>