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

Next.js中getInitialProps未向类组件传递props返回空结果如何排查?

问题原因
  • 核心错误是getInitialProps的返回值格式不符合Next.js规范:Next.js 页面的getInitialProps直接返回要注入组件props的对象,不需要在外层包裹props字段。你当前返回{props: {test: 'test 123'}},实际传递到组件的props结构为{props: {test: 'test 123'}},因此this.props.test自然为undefined。
  • 可选检查:你写的文件名为indx.js,确认是否为拼写错误,首页标准文件名为index.js,拼写错误会导致路由匹配异常。
修复代码

修改index.js中getInitialProps的返回逻辑即可,_app.js代码无需改动:

import React from 'react'
export default class Home extends React.Component {
  static async getInitialProps(ctx) {
    const test = 'test 123'
    // 直接返回props对象,无需外层嵌套props字段
    return { test }
  }
  render() {
    console.log(this.props.test)
    return (
      <>
        <h1>{this.props.test}</h1>
      </>
    )
  }
}
效果验证

修复后重启开发服务,控制台会正常打印test 123,页面h1标签也会显示对应内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:27:00