首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果数据不存在,如何返回null

如果数据不存在,如何返回null
EN

Stack Overflow用户
提问于 2022-07-08 22:21:23
回答 2查看 109关注 0票数 0

我如何对我传递的所有数据使用像if(!testimonials) return null这样的东西。它现在只显示空数组。我不知道该在哪里使用“如果-否则”的规则。

aboutus.tsx

代码语言:javascript
复制
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);

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

const aboutus = ({ testimonials, clients , stats}: any) => {
  return (
    <>
      <AboutComponent
        testimonials={testimonials}
        clients={clients}
        stats={stats}
      />
    </>

谢谢你的帮助!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-08 22:35:49

如果三元算子属性可以为null,则可以使用该属性:

代码语言:javascript
复制
<AboutComponent
        testimonials={!testimonials ? null : testimonials}
        clients={clients}
        stats={stats}
      />
票数 1
EN

Stack Overflow用户

发布于 2022-07-08 22:33:16

我不知道我是否正确理解,但看起来您希望这个组件是动态的

你可以用这个

代码语言:javascript
复制
<>
  {!!testimonials && (
       <AboutComponent
        testimonials={testimonials}
        clients={clients}
        stats={stats}
      />
  )}
</>

这样,您就可以将“证明”转换为布尔值,并且只显示“证明”是否为真的。

如果你需要其他的话,你可以这样做

代码语言:javascript
复制
<>
  {testimonials ? (
       <AboutComponent
        testimonials={testimonials}
        clients={clients}
        stats={stats}
      />
  ) : (
    <h1>testimonials does not exist</h1>
  )}
</>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72917547

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档