繁体   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