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

Next.js中getStaticProps返回数据控制台可见但页面不渲染

问题:Next.js 页面使用getStaticProps传递数据后JSX渲染空白无报错

我正在将原React项目重构为Next.js,现有一个使用getStaticProps及配套getStaticPaths的页面。问题在于,接口返回的product数据可通过console.log在控制台正常显示,但在页面JSX中渲染product.name、product.price时页面空白,且无任何报错信息。

相关代码

getStaticProps 和 getStaticPaths 代码

export async function getStaticProps(context) {
    try {
        const slug = context.params.slug;
        const response = await fetch(`http://127.0.0.1:8000/api/product/${slug}/`);
        const data = await response.json();
        return {
            props: { product: data },
        };
    } catch (error) {
        console.log(error)  
    }
}

export const getStaticPaths = async () => {
    try {
        const response = await fetch(`http://127.0.0.1:8000/api/product/list/`);
        const data = await response.json();
        const allSlugs = data.map(item => item.slug)
        const paths= allSlugs.map(slug => ({params:{slug:slug}}))
        return {
            paths,
            fallback: false,
        }
    } catch (error) {
        console.log(error)   
    }
}

页面JSX代码

function Product({product}){
    console.log(product) // 控制台能正常显示product数据
    return <div>
        以下内容渲染空白,无报错
        <h2>{product.name}</h2>
        <p> {product.price}</p>
    </div>
}
export default Affidavit

问题原因及解决办法

1. 组件导出错误(核心问题)

页面组件定义为Product,但导出时写的是export default Affidavit,这会导致Next.js无法正确加载页面组件,最终页面空白。

解决:
将导出语句改为:

export default Product

2. 数据结构嵌套问题(次要排查点)

虽然控制台能打印product,但需确认name和price是否直接属于product对象。比如部分接口会返回嵌套结构(如{ data: { name: 'xxx', price: 100 } }),此时直接访问product.name会得到undefined,渲染时不会报错但内容空白。

排查:
在控制台展开product对象,查看字段层级。如果是嵌套结构,需调整JSX中的访问路径,比如product.data.name。

3. getStaticProps错误处理不完善

当前getStaticProps的catch块仅打印错误,未返回任何props。如果请求失败,product会是undefined,此时访问product.name会导致静默失败(开发模式下通常会报错,但生产模式可能空白)。

优化:
在catch块中添加错误处理逻辑,比如返回404:

catch (error) {
    console.log(error)
    return {
        notFound: true
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:42:14