Gatsby中处理Contentful GraphQL数据时map方法报错如何解决?
问题根因
- 缺少数据非空校验:Gatsby页面初始渲染时,GraphQL拉取的Contentful数据还未返回,
data.allContentfulWorksExamplePost为undefined,直接访问它的edges属性再调用map方法会抛出异常。 map回调无返回值:你当前在map的回调函数中只执行了console.log,没有返回合法的React节点,即使数据正常也无法渲染内容,不符合JSX语法要求。
修复方案
修改代码如下即可:
return <Layout> <SEO title="Page two" /> <h1>This is our work page</h1> <p>Here are examples of our recent work</p> {/* 可选链做非空拦截,空值兜底展示加载提示/无数据提示 */} {data?.allContentfulWorksExamplePost?.edges?.map(item => { console.log('item', item) // 替换为你实际需要渲染的作品内容结构 return <div key={item.node.id}> <h3>{item.node.title}</h3> <p>{item.node.description}</p> </div> }) ?? <p>正在加载作品数据...</p>} <p>Welcome to page 2</p> <Link to="/">Go back to the homepage</Link> </Layout>
额外校验建议
如果修改后仍有问题,可前往Gatsby内置GraphiQL调试工具(本地开发默认地址为http://localhost:8000/___graphql),运行你写的页面查询语句,确认返回结构中确实存在allContentfulWorksExamplePost.edges字段,且字段层级和你代码中访问的完全一致。
内容的提问来源于stack exchange,提问作者Ropenfold
相关产品推荐
相关产品推荐

