如何在查询中处理 "Cannot read property 'node' of null"

How to handle "Cannot read property 'node' of null" in a query

我是 React/Gatsby 的新手,正在使用 Apollo 进行查询。 问题是,如果没有标题或图像,它会说“无法读取 属性 'node' of null”。我明白了,因为如果我不在我的无头 CMS 中设置标题或图像,就没有数据可读。

我怎样才能使它有条件,以便 如果 'title' 为空,则不渲染 它。随时欢迎关于我的代码的任何其他建议或提示!

这是我的代码示例

import React from "react"
import Container from "react-bootstrap/Container"
import Image from "react-bootstrap/Image"
import { useQuery, gql } from "@apollo/client"

const APOLLO_QUERY = gql`
  {
    posts {
      nodes {
        title
        databaseId
        content(format: RENDERED)
        featuredImage {
          node {
            sourceUrl
          }
        }
      }
    }
  }
`

const ApolloTest = () => {

  const { data } = useQuery(APOLLO_QUERY)

  return (
    <Container>
      {data &&
        data.posts.nodes.map(post => {
          return (
            <article key={post.databaseId}>
              <h3>{post.title}</h3>
              <p>{post.content}</p>
              <Image
                src={post.featuredImage.node.sourceUrl}
                alt={post.title}
                style={{ width: "150px" }}
                fluid
              ></Image>
            </article>
          )
        })}
    </Container>
  )
}

export default ApolloTest

我建议短路评估 在尝试呈现之前先检查信息是否存在。一个简单的例子是 {post.title && <h3>{post.title}</h3>},如果 post.title 为真,它只会渲染 h3 和其中的所有内容。您也可以扩展它以适用于图像:

return (
  <Container>
    {data?.posts.nodes.map(post => {
      return (
        <article key={post.databaseId}>
          {post.title && <h3>{post.title}</h3>}
          <p>{post.content}</p>
          {post.featuredImage && <Image
            src={post.featuredImage.node.sourceUrl}
            alt={post.title}
            style={{ width: "150px" }}
            fluid
          />}
        </article>
      )
    })}
  </Container>
)