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
相关产品推荐
相关产品推荐

