【发布时间】:2021-08-26 17:42:01
【问题描述】:
我有一个 GraphQL 查询来显示来自 Wordpress Headless 的帖子,但我有一些帖子没有featuredImage,因此我得到了TypeError: Cannot read property 'node' of null。
即使没有提供featuredImage,我如何让我的查询接受可空元素从而显示页面?
这是我的查询:
import Image from "next/image";
export default function Post(data) {
const post = data.post;
return (
<div>
<h1>{post.title}</h1>
<Image width="640" height="426" src={post.featuredImage.node.sourceUrl} />
<article dangerouslySetInnerHTML={{ __html: post.content }}></article>
</div>
);
}
export async function getStaticProps(context) {
const res = await fetch("https://www.torontowebmarketing.ca/graphql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `
query SinglePost($id: ID!, $idType: PostIdType!) {
post(id: $id, idType: $idType) {
title
slug
content
featuredImage{
node {
sourceUrl
}
}
}
}
`,
variables: {
id: context.params.slug,
idType: "SLUG",
},
}),
});
const json = await res.json();
return {
props: {
post: json.data.post,
},
};
}
【问题讨论】:
-
谢谢!这行得通。将此作为答案
标签: wordpress graphql next.js headless-cms