简体   繁体   English

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

[英]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.

相关问题 为什么 React 条件渲染会渲染 NaN? - Why does React conditional rendering render NaN? 为什么在使用 redux 时,这两种情况下的反应渲染不同? - Why does react render differently in these two cases when using redux? 使用 redux 和 react 时渲染条件 jsx 的正确方法是什么 - What is correct way to render conditional jsx when using redux with react React 没有呈现正确的条件元素 - React does not render correct conditional element 为什么我的组件在使用 React 的 Context API 和 useEffect 钩子时渲染了两次? - Why does my component render twice when using React's Context API and the useEffect hook? 为什么 React 组件会渲染? - Why does the React component render? 如何使用 Jest 在 React 中测试条件渲染? 包装器是否在新组件渲染时更新? - How to test conditional rendering in React using Jest? Does the wrapper update on new component render? 在React Router中使用browserHistory而不是hashHistory时,应用程序不呈现 - App does not render when using browserHistory instead of hashHistory in React Router 使用自定义条件渲染组件时,类型 JSX.Element 不可分配给类型 React.ReactNode - Type JSX.Element is not assignable to type React.ReactNode when using customed conditional render component React Conditional Render和Navbar - React Conditional Render and Navbar
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM