You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

组件中getStaticProps返回值始终为undefined的排查求助

问题:getStaticProps返回的posts始终为undefined,触发map调用类型错误

我严格按照网上示例使用getStaticProps,但组件获取到的返回值始终为undefined,代码中的posts一直是undefined,出现类型错误:Cannot read properties of undefined (reading "map")。我怀疑可能是防火墙问题,但想先确认代码本身是否存在问题,相关代码如下:

import { GraphQLClient, gql } from "graphql-request";
import { BlogCard } from "../../components/BlogCard";

const graphcms = new GraphQLClient(
  "this is an api string"
);

const QUERY = gql`
  {
    posts {
      title
      datePublished
      content {
        html
      }
    }
  }
`;

export async function getStaticProps() {
  const { posts } = await graphcms.request(QUERY);

  return {
    props: {
      posts,
    },
    revalidate: 10,
  };
}

export default function Home({ posts }) {
  return (
    <main>
      {posts.map((post) => (
        <BlogCard
          title={post.title}
          author={post.author}
          coverPhoto={post.coverPhoto}
          key={post.id}
          datePublished={post.datePublished}
          slug={slug}
        />
      ))}
    </main>
  );
}

代码本身存在的几个问题

  • GraphQL查询字段缺失:你在QUERY里只请求了title、datePublished、content{html},但组件里却要用到post.author、post.coverPhoto、post.id、slug这些字段,这些字段根本没在查询中获取,就算请求成功,这些值也会是undefined(不过这不是posts为undefined的直接原因)。

  • 未处理请求异常:getStaticProps里没有错误捕获逻辑,如果GraphQL请求失败(比如API地址错误、权限验证失败、网络问题),会直接抛出错误,导致posts无法正常赋值。建议用try/catch包裹请求,输出错误信息排查:

    export async function getStaticProps() {
      try {
        const { posts } = await graphcms.request(QUERY);
        return {
          props: { posts: posts || [] },
          revalidate: 10,
        };
      } catch (error) {
        console.error("GraphQL请求失败:", error);
        return {
          props: { posts: [] },
          revalidate: 10,
        };
      }
    }
    
  • API地址是占位符:你写的"this is an api string"是无效的API地址,必须替换为GraphCMS提供的真实API端点,格式通常是https://api-<区域>.hygraph.com/v2/<项目ID>/master。

  • 响应结构可能不符预期:部分GraphQL服务的响应会嵌套在data字段下,你可以先打印完整响应确认结构:

    const response = await graphcms.request(QUERY);
    console.log("GraphQL响应:", response);
    const posts = response.posts || [];
    

    同时给posts设置默认空数组,避免后续map调用报错。

  • 组件兜底处理:在组件接收props时给posts设置默认值,就算getStaticProps返回undefined,也不会触发报错:

    export default function Home({ posts = [] }) {
      // ... 原有代码
    }
    

内容的提问来源于stack exchange,提问作者Tyler Wong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 22:25:31