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

Next.js getServerSideProps获取数据无法传递至UI组件问题排查

排查Next.js getServerSideProps传递props为空的问题
  • 检查getServerSideProps的返回格式
    这是最常见的问题:必须返回一个包含props字段的对象,否则组件无法接收到数据。示例:

    export async function getServerSideProps() {
      const res = await fetch('http://localhost:8080/api/hbreport');
      const data = await res.json();
      // 正确写法:用props字段包裹要传递的数据
      return { props: { data } };
      // 错误写法:直接返回数据或未用props包裹
      // return data;
      // return { data };
    }
    

    控制台能打印数据但组件收不到,大概率是没按规范用props字段封装返回值。

  • 确认组件接收props的方式
    函数组件需通过参数直接接收props:

    export default function ReportPage({ data }) {
      return <div>{JSON.stringify(data)}</div>;
    }
    

    如果是类组件,要通过this.props.data访问,检查是否存在绑定或接收逻辑错误。

  • 核对API返回的数据结构
    控制台打印的数据可能是嵌套结构(比如API返回{ data: [实际列表] }),这时候需要解构出真实数据再传递:

    export async function getServerSideProps() {
      const res = await fetch('http://localhost:8080/api/hbreport');
      const responseData = await res.json();
      // 若API返回层级嵌套,需提取实际数据字段
      return { props: { data: responseData.data } };
    }
    

    可以在控制台打印responseData的完整结构,确认目标数据所在的层级。

  • 添加异步操作的错误处理
    可能存在隐藏的请求错误(比如状态码非200、JSON解析失败),虽然控制台能打印数据,但可能是缓存的旧数据。添加try/catch排查:

    export async function getServerSideProps() {
      try {
        const res = await fetch('http://localhost:8080/api/hbreport');
        if (!res.ok) {
          throw new Error(`请求失败:状态码${res.status}`);
        }
        const data = await res.json();
        console.log('获取到的数据:', data);
        return { props: { data } };
      } catch (error) {
        console.error('请求错误:', error);
        // 返回默认props避免组件崩溃
        return { props: { data: [] } };
      }
    }
    
  • 确认getServerSideProps的使用范围
    这个函数只能在pages目录下的页面组件中直接导出使用,如果定义在子组件、非页面组件中,不会触发执行,组件自然接收不到props。确保函数所在文件是pages目录下的页面文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:26:27