为什么"0"在对array.length&&的短路评估时进行渲染...` [英] Why "0" is rendered on short-circuit evaluation of `array.length && ...`
问题描述
目前,我看到这样的行为:
Currently, I see behavior like this:
render() {
const list = [];
return (
<div>
{ list.length && <div>List rendered</div> }
</div>
)
}
我希望在这种情况下什么也不会渲染,而是渲染字符串"0"(字符串"0"是 list.length
).我不知道为什么有人可以帮我向React解释这种情况吗?
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?
推荐答案
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:
(有些虚假的表情)&&expr短路评估为虚假的表情
(some falsy expression) && expr is short-circuit evaluated to the falsy expression
因此,在行 {list.length&&< div>列表呈现的</div>}
,同时它的评估结果也很虚假在渲染器上不会被忽略,与 false
, null
, undefined
或 true
.
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>
这篇关于为什么"0"在对array.length&&的短路评估时进行渲染...`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!