如何让GraphQL Query支持可空字段解决无featuredImage报错问题
解决方法
报错是因为未设置特色图的文章返回的featuredImage字段为null,直接访问null.node就会触发类型错误,按以下方案修改即可兼容空值场景:
- 前端组件增加空值判断和条件渲染
使用JS可选链操作符?.安全访问嵌套属性,同时仅当特色图存在时才渲染Next.js的Image组件,也可以自定义占位图替代缺失的特色图。修改后的组件代码如下:
import Image from "next/image"; export default function Post(data) { const post = data.post; // 安全获取特色图地址,不存在则为undefined const featuredImgUrl = post.featuredImage?.node?.sourceUrl; return ( <div> <h1>{post.title}</h1> {/* 仅当存在特色图时渲染,也可以替换为默认占位图逻辑 */} {featuredImgUrl && ( <Image width="640" height="426" src={featuredImgUrl} alt={post.title} /> )} <article dangerouslySetInnerHTML={{ __html: post.content }}></article> </div> ); }
- 可选:服务端数据预处理兜底
如果需要统一给没有特色图的文章配置默认占位图,也可以在getStaticProps里提前处理数据,避免组件层重复判断:
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(); const post = json.data.post; // 预处理:没有特色图时赋值默认占位图地址,可替换为你自己的占位图链接 if (!post.featuredImage?.node?.sourceUrl) { post.featuredImgUrl = '/default-post-cover.jpg'; } else { post.featuredImgUrl = post.featuredImage.node.sourceUrl; } return { props: { post, }, }; }
处理后组件里可以直接用post.featuredImgUrl渲染即可,无需额外判断。
提示:WPGraphQL本身的
featuredImage字段原生支持可空,不需要额外修改查询语句即可返回空值,只需要前端做好空值兼容即可。
内容的提问来源于stack exchange,提问作者Ilir
相关产品推荐
相关产品推荐

