簡體   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