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

Next.js对接Sanity获取数据不存在时如何返回null

判空逻辑实现方案

你可以根据需求选择以下两个位置编写判断逻辑,注意Sanity查询无匹配结果时返回的是空数组[],而JS中空数组属于truthy值,仅写if(!testimonials)无法拦截空数组场景,必须补充长度判断。

方案1:在getServerSideProps服务端层拦截

如果要在数据传到组件前就做校验,数据不全时直接返回404状态,就在fetch到数据后、返回props前加判断:

export const getServerSideProps = async ({ params }: any) => {
  
  const query = `{
  'stats': *[ _type == "stats"] {
           _id,
        title,
        stat,
        icon
  },
  'testimonials': *[ _type == "testimonials"] {
    _id,
        description,
        author,
        job,
  },
  'clients': *[ _type == "clients"] {
    _id,
        client,
        mainImage,
  },
}`;
  const props = await sanityClient.fetch(query);

  // 任意一类数据不存在/为空,直接返回404
  if (!props.testimonials?.length || !props.clients?.length || !props.stats?.length) {
    return { notFound: true }
  }

  return { props: { 
     testimonials: props.testimonials,
     clients: props.clients,
     stats: props.stats,
   } 
  }; 
  
};

方案2:在页面组件渲染层拦截

如果要实现数据不全时直接返回null不渲染页面内容,就在组件函数的最开头、return JSX前加判断:

const aboutus = ({ testimonials, clients , stats}: any) => {
  // 任意一类数据不存在/为空,直接返回null不渲染
  if (!testimonials?.length || !clients?.length || !stats?.length) {
    return null
  }

  return (
    <>
      <AboutComponent
        testimonials={testimonials}
        clients={clients}
        stats={stats}
      />
    </>
  )
}

提示:两种方案可以根据业务需求选择,如果你希望数据缺失时页面直接不占位不渲染,选方案2;如果希望数据缺失时直接走404页面逻辑,选方案1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 00:24:43