【问题标题】:Make GraphQL query nullable使 GraphQL 查询可以为空
【发布时间】: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


【解决方案1】:

不是查询/类型问题,对于数据集/树中的某些道具具有空值是很好/合法的(在 Playground 文档中探索类型)。

只需准备您的渲染函数来处理空值,缺少一些值。您可以使用条件渲染来做到这一点,在这种情况下:

{post.featuredImag && <Image....>}

【讨论】:

    猜你喜欢
    • 2017-02-19
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2020-10-22
    • 2020-05-21
    • 2018-11-10
    • 1970-01-01
    相关资源
    最近更新 更多