问题描述
我习惯于这样编写渲染可选组件:
I'm used to write render optional Components like this:
var Foo = React.createClass({
render: function() {
var length = 0;
return <div>Foo {length && <Bar />}</div>;
}
});
此速记if
在 if/else中提到在JSX指南中作为立即调用的函数表达式.但是,自从我最新的React更新以来,它开始渲染0
而不是null
.
This shorthand if
is mentioned in the if/else in JSX guide as immediately-invoked function expression. However, since my latest update of React, it started to render 0
instead of null
.
为什么会这样?
推荐答案
&&
运算符首先计算左手表达式,如果左手表达式求值虚假,则返回该值.左手表达,而无需进一步评估.
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.
因此,(0 && "Bar")
的计算结果为0
,然后将其呈现为字符串.如果所有伪造的值都在渲染中被丢弃,则无法在React中打印0
,例如length is { 0 }
仅打印length is
.
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
.
但是,如果将false
,null
和undefined
用作子级,则会被React渲染器丢弃,它是正是针对此用例:
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
这篇关于JSX不会将表达式中的整数评估为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!