使用短路(&&)条件组件的React显示0而不是什么 [英] React showing 0 instead of nothing with short-circuit (&&) conditional component
问题描述
我有以下简单的短路语句,应该不显示组件或不显示任何内容:
I have the following simple short-circuit statement that should show either a component or nothing:
{profileTypesLoading& < GeneralLoader />}
如果该语句为假,则呈现 0
而不是什么。
If the statement is false, it renders a 0
instead of nothing.
我已经完成了 console.log(profileTypesLoading)
只是为了快速了解 profileTypesLoading
属性的状态为,并且按预期是1或0。 0应该为假...什么也不会渲染。是吗?
I have done a console.log(profileTypesLoading)
just to see quickly what the status of the profileTypesLoading
property is and it's either 1 or 0 as expected. 0 should be false... causing nothing to render. Right?
知道为什么会这样吗?
推荐答案
您的条件是虚假的,因此不会返回第二个参数(< GeneralLoader />
),它将返回 profileTypesLoading
,这是一个数字,因此React将渲染它,因为React会跳过 typeof
boolean
或 undefined
并将呈现 typeof
string
或 number
:
Since your condition is falsy and so doesn't return the second argument (<GeneralLoader />
), it will return profileTypesLoading
, which is a number, so react will render it because React skips rendering for anything that is typeof
boolean
or undefined
and will render anything that is typeof
string
or number
:
为了安全起见,您可以使用三元表达式 {condition? <组件/> :null}
或布尔值将条件转换为 {!! condition&& <组件/>}
To make it safe, you can either use a ternary expression {condition ? <Component /> : null}
or boolean cast your condition like {!!condition && <Component />}
这篇关于使用短路(&&)条件组件的React显示0而不是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!