【发布时间】:2021-04-09 16:25:14
【问题描述】:
即使我的查询在 GraphQL Explorer 中为我提供了正确的结果,我也会收到此错误。
我正在尝试为文章加载封面图片,但看不到哪里出错。
有很多博客文章和相同的问题,但我没有找到可以解决此错误的正确答案。
错误:TypeError:无法读取 null 的属性“childImageSharp”
这是我迄今为止尝试过的:
Mdx
---
title: Hello World - from mdx!
date: 2019-06-01
published: true
tags: ['react', 'javascript']
---
盖茨比组件
const Blog = ({ data }) => {
const tags = data.allMdx.group
const posts = data.allMdx.nodes
return (
<Layout>
<div className="hero blog-section">
<div className="hero-body">
<div className="container">
<h1 className="home-title is-size-1">Blog</h1>
<h3 className="home-subtitle is-size-4">
Thoughts about programming, design and random stuff
</h3>
<div className="tags"></div>
<div class="tags">
{tags.map(tag => (
<Link
to={`/tags/${kebabCase(tag.fieldValue)}/`}
className="tag is light"
>
{tag.fieldValue}
</Link>
))}
</div>
{posts.map(({ id, excerpt, frontmatter, fields }) => (
<Link to={fields.slug}>
<div key={id} className="card is-fullimage mb-1">
<Img fluid={frontmatter.cover.childImageSharp.fluid} />
<div className="card-stacked">
<div className="card-content">
<time className="home-red">{frontmatter.date}</time>
<h1 className="is-size-4">{frontmatter.title}</h1>
<p>{excerpt}</p>
<span className="home-red">
{fields.readingTime.text}
</span>
</div>
</div>
</div>
</Link>
))}
</div>
</div>
</div>
</Layout>
)
}
查询
export const query = graphql`
query SITE_INDEX_QUERY {
allMdx(
sort: { fields: [frontmatter___date], order: DESC }
filter: { frontmatter: { published: { eq: true } } }
) {
group(field: frontmatter___tags) {
fieldValue
}
nodes {
id
excerpt(pruneLength: 100)
frontmatter {
tags
title
date(formatString: "MM/DD/YYYY")
cover {
publicURL
childImageSharp {
fluid(maxWidth: 2000, traceSVG: { color: "#639" }) {
tracedSVG
}
}
}
}
fields {
slug
readingTime {
text
}
}
}
}
}
`
gatsby-config.js
module.exports = {
siteMetadata: {
title: `Lorem Ipsum Blog`,
description: `Lorem ipsum.`,
},
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/images`,
name: `images`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/posts`,
name: `posts`,
},
},
{
resolve: `gatsby-plugin-mdx`,
options: {
extensions: [`.mdx`, `.md`],
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 630,
},
},
],
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
`gatsby-plugin-sass`,
`gatsby-plugin-dark-mode`,
`gatsby-plugin-feed`,
`gatsby-remark-reading-time`,
],
}
提前致谢
【问题讨论】:
标签: reactjs graphql gatsby gatsby-image