JSX doesn't evaluate integer in expression as boolean

允我心安 提交于 2019-12-01 21:00:53

The && operator evaluates the left-hand expression first, and if the left-hand expression evaluates to something falsy it returns the value of the left-hand expression without evaluating further.

So (0 && "Bar") evaluates to 0 which is then rendered as a string. If all falsy values were discarded in the rendering then there would be no way to print a 0 in React, for example length is { 0 } would only print length is.

However false, null and undefined are discarded by React renderer if used as a child, and it's exactly for this use case:

length is { 0 } // length is 0
length is { NaN} // length is NaN
length is { null } // length is
length is { false } // length is
length is { undefined } // length is

You need the left-hand expression of your && operator to return one of those three, the simplest being a boolean:

( !!length && "Bar" ) // evaluates to false, doesn't print
( (length > 0) && "Bar" ) // evaluates to false, doesn't print
( (length != 0) && "Bar" ) // evaluates to false, doesn't print
( Boolean(length) && "Bar" ) // evaluates to false, doesn't print

I would write it like

length ? <Bar /> : void(0)

React will not render something that is undefined, and with void(0) you guarantee that not any library had changed the value of undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!