[英]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: 我在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
}
}
}
}
`
I tried to use StaticQuery
with function component but it didn't work. 我尝试将StaticQuery
与功能组件一起使用,但没有用。 So, I want to stick to the class component syntax. 因此,我想坚持使用类组件语法。
Here, the query executes fine in http://localhost:8001/___graphql
在这里,查询可以在http://localhost:8001/___graphql
How do I access query data in react
class component ? 如何访问react
类组件中的查询数据?
Only page component files can export a query
variable to query like your example shows. 只有页面组件文件才能导出query
变量以进行查询,如您的示例所示。 See Use a page query in the Gatsby documentation. 请参阅Gatsby文档中的使用页面查询 。
Here's an example of StaticQuery
usage with a class component. 这是StaticQuery
与类组件StaticQuery
使用的示例。 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 . 您也可以考虑使用Gatsby的useStaticQuery
hook 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.