Graphql Can';t从contentful查询数据到gatsby项目
不要让查询满足于工作。 接收错误消息:Graphql Can';t从contentful查询数据到gatsby项目,graphql,gatsby,contentful,Graphql,Gatsby,Contentful,不要让查询满足于工作。 接收错误消息: TypeError:无法读取未定义的属性“allContentfulMagArticle” 数据在Posts组件中未定义。我看不出我做错了什么 import { graphql } from 'gatsby'; import Post from "./post.js"; import './posts.css'; export const query = graphql` query { allContentfulMa
TypeError:无法读取未定义的属性“allContentfulMagArticle”
数据
在Posts组件中未定义。我看不出我做错了什么
import { graphql } from 'gatsby';
import Post from "./post.js";
import './posts.css';
export const query = graphql`
query {
allContentfulMagArticle{
edges{
node{
index
title
name
subHeading
extract {
raw
}
slug
}
}
}
}
`
const Posts = ({ data }) => {
return (
<section className="posts">
<ul className="post-list">
{data.allContentfulMagArticle.edges.map(({ node }) => (
<Post
key={node.index}
id={node.index}
node={node}
title={node.title}
name={node.name}
// image={node.frontmatter.featuredImage.childImageSharp.fluid}
subheading={node.subheading}
body={node.extract.raw}
/>
))}
</ul>
</section>
)
}
export default Posts
您使用“组件”一词来描述您的帖子
,但您使用的查询仅在页面中或在createPage上下文中有效(在模板文件中也是如此)。如果您确实在一个组件中,那么这就是问题所在。如果没有,那么我不清楚是哪里出了问题,我使用相同的模式(例如:data.edges.node.map()
),它对我有效
我注意到的另一个区别是在
gatsby config
中,我定义了一个环境
键。如果没有定义,我不确定行为是什么,可能默认为master
,因此您可能还需要确认您处于正确的环境中。好吧,问题显然来自Contentful插件。您是否正确获取了环境变量?您是否尝试过在localhost:8000/\uuuuuu图形ql
操场中进行查询,以检查是否构造良好?是的,它在localhost:8000/\uuuuuu图形ql
中有效@FerranBuireuYes,我实际上刚刚意识到这是一个问题(我更仔细地阅读了错误日志),这个查询在非页面上下文中不起作用,我需要它作为Posts组件。所以我改为useStaticQuery,它现在可以工作了@米歇尔
require('dotenv').config({
path: `.env`,
})
module.exports = {
siteMetadata: {
title: `XX`,
description: `XX`,
author: `Lisa Lee`,
url: `https://www.tortmagazine.com`
},
plugins: [
`gatsby-plugin-react-helmet`,
'gatsby-plugin-fontawesome-css',
'gatsby-plugin-sharp',
`gatsby-transformer-sharp`,
`gatsby-transformer-remark`,
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/`,
},
},
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: process.env.GATSBY_CONTENTFUL_SPACE_ID,
accessToken: process.env.GATSBY_CONTENTFUL_ACCESS_TOKEN,
},
},
],
}