Reaction Render逻辑&VS三元运算符(&&VS) [英] react render Logical && vs Ternary operator

查看:39
本文介绍了Reaction Render逻辑&VS三元运算符(&&VS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在反应render()中,当x的值等于1时,逻辑&;&;和三元运算符都将显示Hello,并且两者在语法上都是正确的。当我不想显示条件的其他部分时,我总是使用&;&;,但我遇到了一个代码库,在该代码库中,大多数地方使用的是null,而不是&;&;。使用一种方法比使用另一种方法是否有任何性能提升或任何其他优势?

return (
    <div>
        <div>{x === 1 && <div>Hello</div>}</div>
        <div>{x === 1 ? <div>Hello</div> : null}</div>
    </div>
);

推荐答案

没有显著的性能差异,但是因为0和空字符串"""falsy" in JavaScript,所以我始终选择三元运算符,以便下一个编辑我代码的人知道我的确切意图。

示例:

const count: number | null = 0;
const firstName: number | null = "";

return (
    <div>
        {/* Was this a bug or is `0` really not supposed to render??
          * This will just render "0". */}
        <div>{count && <>The count is {count}</>}</div>

        {/* Okay got it, there's a difference between `null` and `number` */}
        <div>
          {count == null ? <>No count at all</> : <>Count of {count}</>}
        </div>

        {/* Was this a bug too or is `""` supposed to render nothing?
          * This will just render an empty string. */}
        <div>{firstName && <>My name is {firstName}</>}</div>

        {/* Okay now I see `null` / `undefined` vs. a string */}
        <div>
          {firstName == null ? <>No name</> : <>This *will* render {firstName}</>}
        </div>
    </div>
);

这篇关于Reaction Render逻辑&amp;VS三元运算符(&amp;&amp;VS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆