【问题标题】:TypeError: Cannot read property 'unformatted' of undefinedTypeError:无法读取未定义的属性“未格式化”
【发布时间】:2019-04-11 10:03:36
【问题描述】:

我有一个 GatsbyJS 项目,我使用 StaticQuery 来查询 JSON 文件。我可能错误地查询了我的数据,但是对于其他反应项目,我没有遇到这个问题。我假设结构是一样的。有人可以帮我指出正确的方向吗?

错误:

控制台/检查中的数据结构:

我的代码:

import React from 'react'
import { graphql, StaticQuery } from 'gatsby'

export default () => (
  <StaticQuery
    query={graphql`
      query {
        allDataJson {
          edges {
            node {
              id
              authorship_date {
                unformatted
              }
            }
          }
        }
      }
    `}
    render={data => (
      <header>
        {console.log(data)}
        {console.log(data.authorship_date.unformatted)}
        <p>{data.authorship_date.unformatted} test</p>
      </header>
    )}
  />
)

【问题讨论】:

  • 事件 {console.log(data.id)} 返回未定义。我必须以某种方式闯入数组吗?
  • 正如您在console.log 中看到的,data 没有authorship_date 属性,您应该尝试data.allDataJson.edges[0].node.authorship_date.unformatted
  • 为什么字符串必须这么长?只是好奇它是否可以更短
  • 没有办法,但你可以用别名和新语法让它稍微短一些。我在下面发布一个示例

标签: graphql gatsby


【解决方案1】:

正如您在 console.log 中看到的,数据没有authorship_date 属性,您应该尝试data.allDataJson.edges[0].node.authorship_date.unformatted

为了减少访问(微小)的痛苦,您可以稍微修改查询,使用别名和新的快捷方式(我认为仅在 gatsby ^2.2 中可用)。例如:

  query {
    json: allDataJson {
      nodes {
        id
        authorship_date {
          unformatted
        }
      }
    }
  }

这将减少

data.allDataJson.edges[0].node.authorship_date

data.json.nodes[0].authorship_date

当然,首先将您的节点分配给一个变量总是一个好主意,这样您就不必每次都编写整个内容。

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多