簡體   English   中英

react,gatsby-如何在React類組件中訪問GraphQL查詢數據

[英]react, gatsby - how to access GraphQL query data in react class component

我在gatsby /src/components目錄中有一個名為'Header'的react組件,定義如下:

import React, { Component } from "react"
import { Link } from 'gatsby'
import { StaticQuery, graphql } from 'gatsby'
import Img from "gatsby-image"
import "./header.css"

class Header extends Component {

        constructor(props) {
            super(props);
        }

        render() {
            return(
                <Img fixed={data.file.childImageSharp.fixed} />
            )
        }
    }

    export default Header

    export const query = graphql`
      query {
        file(relativePath: { eq: "logo.png" }) {
          childImageSharp {
            # Specify the image processing specifications right in the query.
            # Makes it trivial to update as your page's design changes.
            fixed(width: 125, height: 125) {
              base64
            }
          }
        }
      }
    `

我嘗試將StaticQuery與功能組件一起使用,但沒有用。 因此,我想堅持使用類組件語法。

在這里,查詢可以在http://localhost:8001/___graphql

如何訪問react類組件中的查詢數據?

只有頁面組件文件才能導出query變量以進行查詢,如您的示例所示。 請參閱Gatsby文檔中的使用頁面查詢

這是StaticQuery與類組件StaticQuery使用的示例。 您必須使用功能性組件包裝類組件,以使其起作用。

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

class CoolThing extends React.Component {
  render () {
    console.log(this.props)
    return (
      <div>
        {this.props.site.siteMetadata.title}

        {/* conditionally render directories */}
        {this.props.directories.edges && (
          <ul>
            {this.props.directories.edges.map((directory) => {
              return <li key={directory.node.id}>{ directory.node.name }</li>
            })}
          </ul>
        )}
      </div>
    )
  }
}

export default () => (
  <StaticQuery
    query={graphql`
      query {
        site {
          siteMetadata {
            title
          }
        }
        allDirectory {
          edges {
            node {
              id
              name
            }
          }
        }
      }
    `}
    render={(data) => (
      <CoolThing site={data.site} directories={data.allDirectory} />
    )}
  />
)

這是該主題的相關討論

您也可以考慮使用Gatsby的useStaticQuery hook

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM