[英]Make GraphQL query nullable
我有一個 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,
},
};
}
不是查詢/類型問題,對於數據集/樹中的某些道具具有 null 值是很好/合法的(在游樂場文檔中探索類型)。
只需准備渲染 function 來處理空值,缺少一些值。 您可以使用條件渲染來做到這一點,在這種情況下:
{post.featuredImag && <Image....>}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.