【问题标题】:Gatsby TypeError - Cannot read property 'id' of undefinedGatsby TypeError - 无法读取未定义的属性“id”
【发布时间】:2019-11-09 16:08:25
【问题描述】:

我正在尝试显示 JSON 文件的结果并不断收到以下错误,但不知道为什么。该查询在 GraphiQL 中运行良好。

错误: TypeError:无法读取未定义的属性“id”

任何想法为什么我会收到错误?

这是我的代码:

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

    const SecondPage = () => (
      <StaticQuery
        query={graphql`
          query StaticDataQuery {
            allStaticdataJson {
              edges {
                node {
                  id
                }
              }
            }
          }
        `}
        render={data => (
          <div>
            <h1>Graphql test:</h1>
            <p>{data.allStaticdataJson.edges.node.id}</p>
          </div>
        )}
      />
    )

    export default SecondPage

【问题讨论】:

    标签: reactjs gatsby


    【解决方案1】:

    看起来您希望 allStaticdataJson 返回一个边数组。如果是这种情况,您需要遍历它们以访问每个节点的 id。

    import React from "react"
    import { StaticQuery, graphql } from "gatsby"
    
        const SecondPage = () => (
          <StaticQuery
            query={graphql`
              query StaticDataQuery {
                allStaticdataJson {
                  edges {
                    node {
                      id
                    }
                  }
                }
              }
            `}
            render={data => (
              <div>
                <h1>Graphql test:</h1>
                {data.allStaticdataJson.edges.map(edge => {
                  <p>{edge.node.id}</p>
                })}
              </div>
            )}
          />
        )
    
        export default SecondPage
    

    【讨论】:

      猜你喜欢
      • 2019-10-15
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 2021-03-09
      • 2020-03-06
      • 2021-09-06
      • 2018-12-02
      • 2021-05-29
      相关资源
      最近更新 更多