使用短路(&&)条件组件反应显示 0 而不是什么都没有 [英] React showing 0 instead of nothing with short-circuit (&&) conditional component

查看:17
本文介绍了使用短路(&&)条件组件反应显示 0 而不是什么都没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的短路语句,应该显示一个组件或什么都不显示:

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?

知道为什么会发生这种情况吗?

Any idea why this would happen?

推荐答案

由于你的条件是假的,所以不返回第二个参数(),它会返回profileTypesLoading,这是一个数字,所以 react 会渲染它,因为 React 会跳过任何 typeof booleanundefined 并将呈现任何 typeof stringnumber:

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 />}

这篇关于使用短路(&amp;&amp;)条件组件反应显示 0 而不是什么都没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆