Don*_*eph 30 javascript conditional-operator jsx reactjs
在react中render()
,当x的值等于1时,逻辑&&和三元运算符都会显示Hello,并且两者在语法上都是正确的。当我不想显示条件的其他部分时,我总是使用 && ,但我遇到过一个代码库,其中大多数地方都使用带有null 的三元运算符而不是 && 。使用一种方法相对于另一种方法是否有任何性能提升或任何其他优势?
return (
<div>
<div>{x === 1 && <div>Hello</div>}</div>
<div>{x === 1 ? <div>Hello</div> : null}</div>
</div>
);
Run Code Online (Sandbox Code Playgroud)
Ros*_*len 28
性能上没有显着差异,但因为0
和 空字符串在 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>
);
Run Code Online (Sandbox Code Playgroud)
有任何性能提升吗
答案是不。
在React Js中,它被称为[Inline If with Logical && Operator]
它之所以有效,是因为在 JavaScript 中,true && 表达式 始终计算为 expression,而 false && 表达式 始终计算为 false 。
因此,如果条件为真,“
&&
”后面的元素将出现在输出中。如果为 false, React 将忽略并跳过它。
小智 5
很好的问题。这是一个 React 陷阱,不仅仅是一个性能问题。这React docs, in my opinion, just dont make this clear enough, and Ross Allen\'s answer is right on and hints at that, but let me try to clarify even more.
\n如果您怀疑您的条件可能会评估为虚假值\xe2\x80\x94 array.length
(因此 React 将渲染数组长度为零)或渲染的字符串可能是空字符串 \xe2\x80\x94使用三元!
否则您可以&&
自由、自信地使用操作员。 An example would be something like
count && count > 3 && (\n <div>In stock</div>\n)\n
Run Code Online (Sandbox Code Playgroud)\n上述检查要么为真,要么为假。所以你很安全。请注意,我们还首先检查以确保count
其真实性,然后 we checked the conditional we\'re looking for specifically. That way we eliminate the possibly of a falsy value being rendered unintentionally.
另一个例子:
\ndata?.order_type && data.order_type === \'patient\' && (\n <div>For patients</div>\n)\n
Run Code Online (Sandbox Code Playgroud)\n这也只能是真或假。注意我还包括了?
作为可选链。这是 JavaScript 中的简写,允许您压缩一些真实性检查。data?.order_type
检查data
为真,如果是,则继续评估,否则将退出评估。
何时使用三元:\nIf your conditional could evaluate to a falsy value. For example:
\nitems.length ? ( // length could be 0\n <div>available</div>\n : null\n)\n
Run Code Online (Sandbox Code Playgroud)\n但是,如果您将上面的内容更改为items.length > 0
,那么您就可以使用&&
operator.
items.length > 0 && ( // length could not be 0\n <div>available</div>\n)\n
Run Code Online (Sandbox Code Playgroud)\n如有疑问,请使您的检查更加具体,并确保在处理条件渲染时您所考虑的是虚假/真实。 It is a gotcha, but once you get the idea behind it, it all makes more sense.
\n 归档时间: |
|
查看次数: |
25407 次 |
最近记录: |