繁体   English   中英

在有条件的情况下使用“ 0”时,为什么在React中渲染“ 0”?

[英]When using `0` in a conditional why does the `0` render in React?

我不知道为什么,但是在页面上呈现的负载为0 最终,我将其范围缩小为零/ 0 ,这不是我要强制成为布尔值。 React不会呈现0以外的任何其他数字

https://codesandbox.io/s/pyk11w5y5j

为什么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>
  );
}

固定

{testParam && !!weirdOh && <h1>Will SHow</h1>}

在react中,数字是完全有效的值,而0只是数字。

确保将其转换为布尔值以避免这种情况,因为false不会呈现任何内容:

{testParam && !!weirdOh && <h1>Will Show</h1>}

要么

{testParam && weirdOh !== 0 && <h1>Will Show</h1>}

如果将weirdOh设置为非零数字,则不会出错,并且<h1>将从表达式返回并呈现。


这与react无关,而只是JS中的&&的工作方式:

  • (1 && 'test') === 'test'因为在获得真实值之后,您转到链中的下一个
  • (0 && 'test') === 0因为一旦您击中一个伪造的值,就会使用该值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM