首页 > 解决方案 > 无法从内容查询数据到 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,
      },
    },
  ],
}

标签: graphqlgatsbycontentful

解决方案


您使用“组件”一词来描述您的Posts,但您使用的查询仅适用于页面或 createPage 的上下文中(在模板文件中也是如此)。如果您确实在一个组件中,那将是问题所在。如果不是,那么我不清楚出了什么问题,我使用相同的模式(例如:)data.edges.node.map(),它对我有用。

我注意到的唯一其他区别是gatsby-config,我定义了一个environment键。我不确定如果没有定义行为是什么,可能默认为,master因此您可能还想确认您处于正确的环境中。


推荐阅读