无法从 contentful 查询数据到 gatsby 项目

Can't query data from contentful to gatsby project

不要让查询满足工作。 收到错误信息: TypeError: Cannot read property 'allContentfulMagArticle' of undefined

data在帖子组件中未定义。看不出我做错了什么。

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

这是我的盖茨比-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 键。如果定义了 none,我不确定行为是什么,可能默认为 master,因此您可能还想确认您处于正确的环境中。