Next.js getServerSideProps返回props在组件内为undefined问题
问题根因
组件接收props的解构写法错误。getServerSideProps 逻辑执行完成后,会把返回值里的props对象直接作为顶层属性传给页面组件,不会额外再套一层props key。你当前写的function Courses({ props }),本质是尝试读取顶层props下名为props的属性,这个属性不存在,所以打印结果为undefined。
你在浏览器网络面板看到服务端正常返回数据,说明接口请求、getServerSideProps的逻辑本身没有问题,问题仅出在组件接收参数的写法上。
修复方案
调整组件的参数解构逻辑,直接读取你传入的data字段即可,参考正确代码:
// 直接解构需要的data字段 function Courses({ data }) { console.log(data); // 此处可正常拿到接口返回的数据 // 其余业务逻辑 } export async function getServerSideProps() { const res = await fetch(process.env.url); const data = await res.json(); return { props: { data } } } export default Courses
如果你需要拿到完整的props对象,直接接收props作为入参即可,不要额外解构props字段:
function Courses(props) { console.log(props.data); // 从props对象上读取data字段 // 其余业务逻辑 }
内容的提问来源于stack exchange,提问作者Eranki
相关产品推荐
相关产品推荐

