graphql - 无法从内容查询数据到 gatsby 项目
问题描述
不要让查询内容满足工作。收到错误信息:
TypeError: Cannot read property 'allContentfulMagArticle' of undefined
data
在 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
这是我的 gatsby-config.js:
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,
},
},
],
}
解决方案
您使用“组件”一词来描述您的Posts
,但您使用的查询仅适用于页面或 createPage 的上下文中(在模板文件中也是如此)。如果您确实在一个组件中,那将是问题所在。如果不是,那么我不清楚出了什么问题,我使用相同的模式(例如:)data.edges.node.map()
,它对我有用。
我注意到的唯一其他区别是gatsby-config
,我定义了一个environment
键。我不确定如果没有定义行为是什么,可能默认为,master
因此您可能还想确认您处于正确的环境中。
推荐阅读
- javascript - 如何从内容中隐藏/模糊电子邮件地址和电话号码?
- django - 即使一切正常,Django表单也没有保存
- firebase - 如何使用 Dart 设置 Firebase 自定义 DocID
- python - 在 GCP 虚拟机上安装 PyCharm
- python - 关于 django/restframework 请求
- webpack - 为什么 webpack 中的入口文件目录“同步”作为最后一个构建/捆绑步骤?
- typescript - 剥离 TypeScript 注释而不进行其他转译(包括第 3 阶段提案)并保留换行符
- javascript - 如何避免使用正则表达式在 unicode 重音后大写字母
- php - 如何在 Symfony 5 中获得内核响应中的用户?
- html - 让两个 div 填满整个页面空间,同时保持垂直滚动