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>
);

相关文章