react render Logical amp;amp; vs Ternary operator(Reaction Render逻辑amp;VS三元运算符(amp;amp;VS))

本文介绍了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". *