从Netlify CMS向Gatsby JS获取数据时遇类型错误求助
Hey there, let's get that error sorted out! The root cause here is how you're accessing the data prop in your class component's render method—class components in React handle props differently than functional components, and that's where the mix-up happened.
What's Wrong
Your render method is trying to destructure data from a parameter that doesn't exist. In class components, props aren't passed directly to the render method as arguments—you need to access them via this.props instead. That's why you're getting the "Cannot read property 'data' of undefined" error.
Additionally, your JSX uses escaped characters (< and >) instead of regular angle brackets, which will cause rendering issues once the prop problem is fixed.
Fixed Code
Here's the corrected version of your component:
import React from 'react' export default class IndexPage extends React.Component { render() { // Access data from this.props instead of a render parameter const { data } = this.props; const { edges: posts } = data.allMarkdownRemark; return ( <section className="section"> <div className="container"> <div className="content"> <h1 className="has-text-weight-bold is-size-2">Your Page Title</h1> {/* Example: Map over posts to render content */} {posts.map(({ node }) => ( <div key={node.id}> <h3><a href={node.fields.slug}>{node.frontmatter.title}</a></h3> <p>{node.excerpt}</p> </div> ))} </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 } } } } } `
Key Changes Made
- Removed
{data}from therendermethod: Class components don't receive props as a parameter torender—usethis.propsinstead. - Destructured
datafromthis.props: This correctly accesses the data returned by your GraphQL query. - Fixed escaped JSX tags: Replaced
<with<and>with>so your markup renders properly. - Added a sample post map: Included a quick example of how to render your posts from the query data (adjust this to match your design needs).
Quick Verification Step
Before testing, confirm your GraphQL query returns data:
- Run your Gatsby site locally with
gatsby develop - Open GraphiQL at
http://localhost:8000/___graphql - Paste your
IndexQueryinto the editor and run it—make sure it returns theallMarkdownRemarkedges you expect.
内容的提问来源于stack exchange,提问作者Federico Resnizky

