【发布时间】:2019-06-22 18:48:22
【问题描述】:
我在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类组件中的查询数据?
【问题讨论】:
-
@BenBachem 是的,得到了
TypeError: Cannot read property 'file' of undefined错误 -
将
console.log(this)放入您的渲染函数中。我想您会发现 data 道具中嵌套了此信息。我想可能是this.props.data.file。 -
嘿@Valay,你必须使用带有组件的StaticQuery。 gatsby 在非页面组件中将忽略全局查询(就像您在此示例中使用的那样)。您对 StaticQuery 有什么问题?
-
另外,如果它在页面组件中,您需要从道具中获取它,所以
this.props.data.file...就像@staypuftman 指出的那样 -
@Derek Nguyen 是的,你是对的。我使用了
StaticQuery和 {...props},它现在工作正常。但是遇到了另一个问题 - 因为我有功能组件,我如何添加窗口滚动事件侦听器。以前我使用的是类组件,并且窗口滚动在 componentDidMount 中工作正常。
标签: reactjs ecmascript-6 graphql gatsby