【发布时间】:2020-01-07 18:36:30
【问题描述】:
我正在使用 gastby 和 wordpress 构建投资组合网站。如果我为它正在工作的网站获取帖子的功能图像,它会显示所有图像。但是,如果我的一篇文章缺少特色图片,我会收到此错误:
TypeError: Cannot read property 'localFile' of null
我找到了this 教程,这个人解决了这个问题,但由于某种原因我没有让它工作。
在索引页面中,我使用了与教程中相同的逻辑 && 运算符方法:
// src/pages/index.js
import React from "react"
import { graphql, Link } from "gatsby"
import Img from "gatsby-image"
import Layout from "../components/layout"
import SEO from "../components/seo"
const IndexPage = ({ data }) => (
<Layout>
<SEO
title={data.wordpressPage.title}
description={data.wordpressPage.excerpt}
/>
<h1>{data.wordpressPage.title}</h1>
<div dangerouslySetInnerHTML={{ __html: data.wordpressPage.content }} />
{data.allWordpressPost.edges.map(edge => (
<Link to={`/post/${edge.node.slug}`} key={edge.node.id}>
//
//
//This should handle the situation if featured image is not set
//
{edge.node.featured_media.localFile.childImageSharp.fixed && (
<div>
<Img
fixed={edge.node.featured_media.localFile.childImageSharp.fixed}
/>
</div>
)}
</Link>
))}
</Layout>
)
export default IndexPage
export const query = graphql`
query {
wordpressPage(title: { eq: "Home" }) {
title
excerpt
content
}
allWordpressPost {
edges {
node {
title
slug
id
featured_media {
localFile {
childImageSharp {
fixed(width: 300, height: 300) {
...GatsbyImageSharpFixed
}
}
}
}
}
}
}
}
`
我对 BlogPost 文件做了同样的事情:
// src/templates/BlogPostTemplate.js
import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"
import Layout from "../components/layout"
import SEO from "../components/seo"
const BlogPostTemplate = ({ data }) => (
<Layout>
<SEO
title={data.wordpressPost.title}
description={data.wordpressPost.excerpt}
/>
<h1>{data.wordpressPost.title}</h1>
<p>
Written by {data.wordpressPost.author.name} on {data.wordpressPost.date}
</p>
{data.wordpressPost.featured_media.localFile && (
<div>
<Img
fixed={
data.wordpressPost.featured_media.localFile.childImageSharp.fixed
}
alt={data.wordpressPost.title}
style={{ maxHeight: 450 }}
/>
</div>
)}
<div
style={{ marginTop: 20 }}
dangerouslySetInnerHTML={{ __html: data.wordpressPost.content }}
/>
</Layout>
)
export default BlogPostTemplate
export const query = graphql`
query($id: Int!) {
wordpressPost(wordpress_id: { eq: $id }) {
title
content
excerpt
date(formatString: "MMMM DD, YYYY")
author {
name
}
featured_media {
localFile {
childImageSharp {
fixed(width: 300, height: 300) {
...GatsbyImageSharpFixed
}
}
}
}
}
}
`
提前致谢!
【问题讨论】: