JSX doesn't evaluate integer in expression as

2020-04-12 01:58发布

问题:

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>;
  }
}); 

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.

Here is a jsfiddle

Why is that happening?

回答1:

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


回答2:

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