我知道查询应该在GatsbyJS项目的layouts文件夹中工作:
但是,我使用GraphQL的一个布局组件的代码不起作用,而我的this.props.data控制台记录为' undefined'。为什么会这样?!?我确定我的代码是正确的,我错过了什么?
这是我的代码:
import React, { Component } from 'react'
export default class Header extends Component {
render() {
// const latestPost = this.props.data.allContentfulBlogPost.edges[1]
// const secondLatestPost = this.props.data.allContentfulBlogPost.edges[2]
console.log(this.props.data)
return (
<div className='container-fluid bottom-margin-large'>
<div className='row'>
<div className='hidden-lg-up header-solink-bar'>0 0 0 0 0</div>
</div>
<div className='row'>
<div className='header-middle'>Blog Title</div>
</div>
<div className='row header-bottom'>
<div className='col-md-6 col-lg-4 header-bottom-input'>
<div><p><span>for recipe updates</span><br />Subscribe to newsletter</p></div>
<form>
<input className='search-input' type='text' name='search' placeholder='search' />
</form>
</div>
<div className='hidden-sm-down col-md-6 col-lg-4 header-bottom-button header-bottom-middle'>
<p><span>date</span><br />name of dessert</p>
</div>
<div className='hidden-md-down col-lg-4 header-bottom-button'>
<p><span>date</span><br />name of dessert</p>
</div>
</div>
</div>
);
}
}
export const headerQuery = graphql`
query headerQuery {
allContentfulBlogPost {
edges {
node {
postTitle
postDate
}
}
totalCount
}
}
`
答案 0 :(得分:2)
在Gatsby中,您只能在“page”或“layout”组件中使用GraphQL查询。这允许Gatsby静态编译您的数据,预取等。从评论中看起来,您已经找到了解决方案。
答案 1 :(得分:0)
从版本2开始,它还可以在StaticQuery
的任何组件槽内使用GraphQL查询,例如:
import React from 'react';
import { StaticQuery, graphql } from 'gatsby';
export const Social = () => (
<div>
<StaticQuery
query={graphql`
{
site {
siteMetadata {
social {
facebook
twitter
instagram
github
}
}
}
}
`}
>
{({
site: {
siteMetadata: { social },
},
}) =>
Object.keys(social).map(title => (
<a
href={social[title]}
key={title}
>
<span>{title}</span>
</a>
))
}
</StaticQuery>
</div>
);
尽管,其行为略有不同-无法使用变量。
您可以在documentation中找到更多信息。