Next.js集成Hygraph报错:Cannot read properties of undefined (reading 'map')
解决Next.js + Hygraph 拉取数据时的「Cannot read properties of undefined (reading 'map')」错误
我在新建的Next.js应用(使用app目录)中尝试从Hygraph拉取数据,遇到错误:Error: Cannot read properties of undefined (reading 'map')。我是Hygraph和Next.js新手,找不到解决办法。已引入graphql和graphql-request,page.js代码如下:
import styles from './page.module.css' import { GraphQLClient, gql } from 'graphql-request' const graphcms = new GraphQLClient( "https://api-eu-west-2.hygraph.com/v2/xxxxxxxxxxxxxx/master" ); const QUERY = gql` { articles { createdAt id publishedAt released slug title updatedAt coverPhoto { url } content { html } } } `; export async function getStaticProps(){ const {articles} = await graphcms.request(QUERY); return { props: { articles, }, revalidate: 10, } } export default function Home({articles}) { return ( <main className={styles.main}> {articles.map((article) => ( <h1>{article.title}</h1> ))} </main> ) }
运行后触发上述错误,更新后的错误显示getStaticProps相关逻辑未生效,组件接收的articles为undefined。
问题原因
你使用的是Next.js App Router(app目录),但getStaticProps是Pages Router(pages目录)专属的数据获取API,在App Router中不会被执行,导致组件的articles参数始终为undefined,调用map时触发错误。
解决方法
在App Router中,直接在组件内部使用异步函数获取数据(App Router原生支持异步组件),修改后的代码如下:
import styles from './page.module.css' import { GraphQLClient, gql } from 'graphql-request' const graphcms = new GraphQLClient( "https://api-eu-west-2.hygraph.com/v2/xxxxxxxxxxxxxx/master" ); const QUERY = gql` { articles { createdAt id publishedAt released slug title updatedAt coverPhoto { url } content { html } } } `; // 直接在组件内部异步获取数据 export default async function Home() { const { articles } = await graphcms.request(QUERY); // 增加兜底处理,避免数据为空时报错 if (!articles) return <main className={styles.main}>暂无文章</main>; return ( <main className={styles.main}> {articles.map((article) => ( // 给列表项添加唯一key <h1 key={article.id}>{article.title}</h1> ))} </main> ) }
额外检查项
- 确认Hygraph的API端点和密钥正确,确保你的请求有权限访问
articles数据集 - 检查Hygraph后台是否有已发布的
articles条目,如果没有,返回的articles会是空数组,可通过兜底处理避免异常 - 生产环境建议给GraphQLClient添加请求头,携带API密钥(如果你的Hygraph项目开启了权限控制):
const graphcms = new GraphQLClient("你的API端点", { headers: { Authorization: `Bearer 你的Hygraph API密钥`, }, });
内容的提问来源于stack exchange,提问作者Lewis
相关产品推荐
相关产品推荐

