Why “0” is rendered on short-circuit evaluation of `array.length && …`

折月煮酒 提交于 2021-01-02 06:35:13

问题


Currently, I see behavior like this:

render() {
   const list = [];
   return (
      <div>
         { list.length && <div>List rendered</div> }
      </div>
   )
}

My expected is nothing rendered with that condition, but string "0" rendered (string "0" is list.length). I don't know why. Anybody can help me explain this case to React?


回答1:


That's basically the way, short-circuit evaluation is designed:

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

(some falsy expression) && expr is short-circuit evaluated to the falsy expression

Thus, 0 is returned with the line { list.length && <div>List rendered</div> }, while it also evaluates as falsy it is not ignored on render as the opposite to false, null, undefined or true.

So, if you want your short-circuit expression to return one of ignored values, you may do it this way:

{ list.length>0 && <div>List rendered</div> }

Following is a quick demo as a proof of concept:

const { render } = ReactDOM

const Component = () => {
  const list = []
  return (
      <div>
         <div>Rendered on <code>{`list.length>0 && <div>List rendered</div>`}</code>:{ list.length>0 && <div>List rendered</div> }</div>
         <div>Rendered on <code>{`list.length && <div>List rendered</div>`}</code>:{ list.length && <div>List rendered</div> }</div>
      </div>
   )
}

render (<Component />, document.getElementById('root'))
code {background-color: grey; color:white;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>



回答2:


This isn't related to React really, but rather to JavaScript directly:

const output = list.length && "foobar";

If list.length is falsy, then output will take its value (so 0 in this case), and not false as one might think.




回答3:


I am a bit late to answer it but i would like to express my understandings.

As other answer by @sp00m explains clearly that it is not related to React but it is a feature of javascript.

What it does?

When the left side is falsy then it will take the value of it as in your case it will be 0 because of the [].length. This causes to print "0" in the DOM.

Solution:

You can make it for a truthy expectation like [].length > 0 or [].length !== 0 or !![].length or make a ternary operator to show the component dom.
The last one converts the falsy/truthy values to a boolean value.



来源:https://stackoverflow.com/questions/60652656/why-0-is-rendered-on-short-circuit-evaluation-of-array-length

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