在反应中render()
当 x 的值等于 1 时,逻辑 && 和三元运算符都会显示Hello并且两者在语法上都是正确的。当我不想显示我的条件的其他部分时,我总是使用 && ,但我遇到过一个代码库,其中大多数地方都使用三元运算符null代替 &&。使用一种方法相对于另一种方法是否有任何性能提升或任何其他优势?
return (
<div>
<div>{x === 1 && <div>Hello</div>}</div>
<div>{x === 1 ? <div>Hello</div> : null}</div>
</div>
);
没有显着的性能差异,但因为0
和空字符串""
are JavaScript 中的“虚假” https://developer.mozilla.org/en-US/docs/Glossary/Falsy我总是选择三元运算符,这样下一个编辑我的代码的人就知道我的确切意图。
Example:
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>
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)