[英]When using `0` in a conditional why does the `0` render in React?
I have no idea why, but I was getting a load of 0
's being rendered on the page. 我不知道为什么,但是在页面上呈现的负载为
0
。 Finally I narrowed it down to a zero/ 0
that I wasn't forcing to be a boolean. 最终,我将其范围缩小为零/
0
,这不是我要强制成为布尔值。 React will not render any other digit other than 0
React不会呈现
0
以外的任何其他数字
https://codesandbox.io/s/pyk11w5y5j https://codesandbox.io/s/pyk11w5y5j
Why does 0
render but 10
for example, does not render? 为什么
0
渲染但10
例如不渲染?
function App() {
const weirdOh = -0;
const testParam = true;
return (
<div className="App">
{testParam && weirdOh && <h1>Will Show</h1>}
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Fix 固定
{testParam && !!weirdOh && <h1>Will SHow</h1>}
Numbers are perfectly valid values in react, and 0
is just that, a number. 在react中,数字是完全有效的值,而
0
只是数字。
Make sure to convert it to a boolean to avoid this, since false
doesn't render anything: 确保将其转换为布尔值以避免这种情况,因为
false
不会呈现任何内容:
{testParam && !!weirdOh && <h1>Will Show</h1>}
or 要么
{testParam && weirdOh !== 0 && <h1>Will Show</h1>}
If you set weirdOh
to a non-zero number, then it won't be falsy, and your <h1>
will be returned from the expression and be rendered. 如果将
weirdOh
设置为非零数字,则不会出错,并且<h1>
将从表达式返回并呈现。
This is not related to react, but simply how &&
in JS works: 这与react无关,而只是JS中的
&&
的工作方式:
(1 && 'test') === 'test'
because after a truthy value, you go to the next one in the chain (1 && 'test') === 'test'
因为在获得真实值之后,您转到链中的下一个 (0 && 'test') === 0
because as soon as you hit a falsy value, that value is used (0 && 'test') === 0
因为一旦您击中一个伪造的值,就会使用该值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.