getServerSideProps传递类对象至页面函数时对象未定义问题
问题原因与解决办法
核心问题有两个:
- 组件参数接收方式错误
Next.js的页面组件接收的是完整的props对象,你直接将参数命名为obj,此时这个obj代表整个props对象,而你在getServerSideProps里返回的是{ obj: ... }结构的props,所以正确做法是从props中解构出obj:
export default function cars({ obj }) { return <h1>counter: {obj.counter}</h1> }
- JSON序列化导致数据类型异常
你用JSON.stringify()把Counter实例转成了字符串,就算正确拿到obj,它也只是个字符串,无法直接通过.counter访问属性。Next.js会自动处理getServerSideProps返回props的序列化工作,直接返回实例即可:
export async function getServerSideProps({ req, res }) { class Counter { constructor() { this.counter = 22 } } const counter = new Counter() return { props: { obj: counter } } }
如果确实需要手动序列化(比如特殊场景),那在组件里要先解析字符串为对象:
export default function cars({ obj }) { const parsedObj = JSON.parse(obj) return <h1>counter: {parsedObj.counter}</h1> }
内容的提问来源于stack exchange,提问作者miguel silvestre
相关产品推荐
相关产品推荐

