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

Next.js无法从Sanity获取数据,返回undefined求助

问题排查:Sanity数据获取返回undefined(Next.js场景)

核心错误点及修复方案

  • 拼写错误:lenght 应为 length
    页面代码中bannerData.lenght && bannerData[0]的lenght是拼写错误,数组长度的正确属性名是length。这个错误会导致逻辑判断始终为false,传递给HeroBanner组件的herobanner值为false,而非预期的bannerData[0],进而在组件内访问属性时出现undefined。

    修正后的代码:

    <HeroBanner herobanner={bannerData.length && bannerData[0]}/>
    
  • 客户端配置缺少createClient导入
    客户端配置代码中使用了createClient但未导入,会导致client变量为undefined,最终getStaticProps中的fetch调用失败,products和bannerData无法获取。

    修正后的客户端配置代码:

    import { createClient } from '@sanity/client'
    import imageUrlBuilder from '@sanity/image-url';
    
    export const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID
    export const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET // "production"
    export const apiVersion = process.env.NEXT_PUBLIC_SANITY_API_VERSION // "2023-05-06"
    export const token = process.env.SANITY_SECRET_TOKEN
    
    export const client = createClient({projectId, dataset, apiVersion, token, useCdn: true})
    
    const builder = imageUrlBuilder(client);
    
    export const urlFor = (source) => builder.image(source);
    

额外排查建议

在getStaticProps中添加错误捕获,方便定位数据获取失败的具体原因:

export async function getStaticProps(){
  try {
    const products = await client.fetch('*[_type == "product"]');
    const bannerData = await client.fetch('*[_type == "banner"]');
    return { props: { products, bannerData } };
  } catch (error) {
    console.error('Sanity数据获取失败:', error);
    return { props: { products: [], bannerData: [] } };
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 23:47:46