简体   繁体   中英

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

I've a react component named 'Header' in /src/components directory in gatsby defined as below:

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
            }
          }
        }
      }
    `

I tried to use StaticQuery with function component but it didn't work. So, I want to stick to the class component syntax.

Here, the query executes fine in http://localhost:8001/___graphql

How do I access query data in react class component ?

Only page component files can export a query variable to query like your example shows. See Use a page query in the Gatsby documentation.

Here's an example of StaticQuery usage with a class component. You have to wrap the class component with a functional component to make it work.

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} />
    )}
  />
)

Here is a related discussion on the topic.

You may also consider using Gatsby's useStaticQuery hook .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM