【问题标题】:Getting data from Netlify CMS to Gatsby JS从 Netlify CMS 获取数据到 Gatsby JS
【发布时间】:2018-05-17 13:28:18
【问题描述】:

我正在使用 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

【问题讨论】:

  • 您还需要这方面的帮助吗?您还没有接受答案,所以问题仍然悬而未决。

标签: reactjs gatsby


【解决方案1】:

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
          }
        }
      }
    }
  }
`

【讨论】:

    【解决方案2】:

    这个语法是解构的:

    render({ data })
    

    这类似于这样做:

    render(props) {
      data = props.data
    }
    

    您遇到的问题是render 没有收到任何参数/道具。

    解决方案是使用this.props,正如@talves 的回答所推荐的那样。

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 2020-06-23
      • 2019-04-18
      • 2019-02-23
      • 1970-01-01
      • 2021-08-29
      • 2023-03-22
      • 2018-09-26
      • 1970-01-01
      相关资源
      最近更新 更多