【问题标题】:Try to catch nodes info from with useStaticQuery of Gatsby尝试使用 Gatsby 的 useStaticQuery 从中获取节点信息
【发布时间】:2023-02-10 01:53:05
【问题描述】:

我正在尝试使用 useStaticQuery 从 GraphQL Gatsby 获取信息,但返回的数据是 undefined,我不明白为什么,因为在我的 http://localhost:8000/___graphql 中我收到了很好的信息。

我的代码不是页面组件,这是我使用Static Query的原因

我的代码是这样的:

import React from "react";
import { useStaticQuery, graphql} from "gatsby";


export default function MenuMD () {
    const { data } = useStaticQuery(
    graphql`
      query {
                allFile(filter: {sourceInstanceName: {eq: "markdown"}}) {
                    edges {
                        node {
                            childrenMarkdownRemark {
                                frontmatter {
                                    slug
                                    title
                                }
                            }
                        }
                    }
                }
      }
    `
    )
    console.log('static data', data);

    return<>Menu from MarkDown</>
}

http://localhost:8000/___graphql 的预期结果是这样的:

{
  "data": {
    "allFile": {
      "edges": [
        {
          "node": {
            "childMarkdownRemark": {
              "frontmatter": {
                "slug": "/projet_m",
                "title": "Projet M"
              }
            }
          }
        },
        {
          "node": {
            "childMarkdownRemark": {
              "frontmatter": {
                "slug": "/projet_n",
                "title": "Projet N"
              }
            }
          }
        }
      ]
    }
  },
  "extensions": {}
}

undefined 返回可能有原因吗?

【问题讨论】:

    标签: javascript reactjs graphql gatsby


    【解决方案1】:

    假设查询在 GraphiQL 环境中工作,并且你的数据结构中有一个 "markdown" sourceInstanceName,试试这样:

    export default function MenuMD() {
      const data = useStaticQuery(
        graphql`
          query {
            allFile(filter: { sourceInstanceName: { eq: "markdown" } }) {
              edges {
                node {
                  childrenMarkdownRemark {
                    frontmatter {
                      slug
                      title
                    }
                  }
                }
              }
            }
          }
        `
      );
      console.log("static data", data);
    
      return <>Menu from MarkDown</>;
    }
    

    在组件而不是页面中使用静态查询没有错,结果必须完全相同(就输出而言)。

    您的数据应该在data.allFile.edges 内(或直接分解为{ allFile }),而不是直接将静态查询的结果解构为data。这就是为什么 data 在您的案例中是 undefined 的原因。

    【讨论】:

    • 你太棒了...只需删除丑陋的 {} 就可以了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 2013-05-06
    • 2023-03-22
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多