首页 > 解决方案 > 从 Netlify CMS 获取数据到 Gatsby JS

问题描述

我正在使用 Netlify CMS + Gatsby 创建一个站点。我已经在 Netlify 中拥有了站点结构和一些数据,但是在将数据导入 Gatsby 时遇到了一些问题。这是我到目前为止所拥有的

import React from 'react'

export default class IndexPage extends React.Component {
  render({data}) {
    const { edges: posts } = data.allMarkdownRemark

    return (
      <section className="section">
        <div className="container">
          <div className="content">
            <h1 className="has-text-weight-bold is-size-2"></h1>
          </div>
        </div>
      </section>
    )
  }
}

export const pageQuery = graphql`
  query IndexQuery {
    allMarkdownRemark(filter: {frontmatter: {templateKey: {regex: "/home-page|media-page/"}}}) {
      edges {
        node {
          excerpt(pruneLength: 400)
          id
          fields {
            slug
          }
          frontmatter {
            title
            templateKey
          }
        }
      }
    }
  }
`

我得到 TypeError: Cannot read property 'data' of undefined

标签: reactjsgatsby

解决方案


不会作为props参数传递到渲染中。

尝试:

import React from 'react'

export default class IndexPage extends React.Component {
  render() {
    const { edges: posts } = this.props.data.allMarkdownRemark

    return (
      <section className="section">
        <div className="container">
          <div className="content">
            <h1 className="has-text-weight-bold is-size-2"></h1>
          </div>
        </div>
      </section>
    )
  }
}

export const pageQuery = graphql`
  query IndexQuery {
    allMarkdownRemark(filter: {frontmatter: {templateKey: {regex: "/home-page|media-page/"}}}) {
      edges {
        node {
          excerpt(pruneLength: 400)
          id
          fields {
            slug
          }
          frontmatter {
            title
            templateKey
          }
        }
      }
    }
  }
`

推荐阅读