[英]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.