在 react render()
当 x 的值等于 1 时,逻辑 && 和三元运算符都将显示 您好并且两者在语法上都是正确的。当我不想显示条件的 else 部分时,我总是使用 &&,但是我遇到了一个代码库,其中大多数地方使用三元运算符 空 代替 &&。使用一种方法相对于另一种方法是否有任何性能提升或任何其他优势?
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>
);
关于javascript - react 渲染逻辑 && vs 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65713434/