简体   繁体   English

html 元素的 React Js 条件渲染未按预期工作

[英]React Js conditional rendering of html element not working as expected

I am adding conditions to display a div element and condition has a variable which comes to be 0 and when it is 0 then 0 displays instead of not displaying anything.我正在添加条件以显示 div 元素,并且条件有一个变量,该变量为 0,当它为 0 时,显示 0 而不是不显示任何内容。

using functional component:使用功能组件:

return (
  <div>
    {flag1 && flag2 &&  data1 && data1.length && data2 && data2.length &&  (
      <div className="answers-heading">Answers ({data2.length})</div>
    )}
  </div>
);

In the above code, I expect if any of the variables are not true then it should simply not display div element but I am getting 0 in UI.在上面的代码中,我希望如果任何变量不正确,那么它不应该显示 div 元素,但我在 UI 中得到 0。 When all conditions true then it works fine.当所有条件都为真时,它工作正常。 I have created stackblitz demo to show how it is working in an unexpected manner.我创建了stackblitz 演示来展示它是如何以意想不到的方式工作的。

Any help would be appreciated.任何帮助,将不胜感激。

Already spent a whole day debugging but could not find the reason.已经调试了一整天,但找不到原因。

return (
  <div>
    {flag1 && flag2 &&  data1 && data1.length && data2 && data2.length ?  (
      <div className="answers-heading">Answers ({data2.length})</div>
    ) : null}
  </div>
);

You should start using ternary instead of only && operator, you will end up with divs with 0 rendered inside.您应该开始使用三元而不是仅使用 && 运算符,您最终会得到内部呈现 0 的 div。 You get 0 because of && operator check which is basically indicating that your condition is "falsey".由于&&运算符检查,您得到 0,这基本上表明您的条件是“错误的”。

Btw, your condition looks fine, you should put that into a const too.顺便说一句,您的情况看起来不错,您也应该将其放入const中。

This might help you out too: React showing 0 instead of nothing with short-circuit (&&) conditional component这也可能对您有所帮助: React 显示 0 而不是短路 (&&) 条件组件

Your issue comes from the fact that data1.length or data2.length is equal to 0 .您的问题来自data1.lengthdata2.length等于0的事实。 It makes your condition resolve to 0 because true && 0 === 0 .它使您的条件解析为0因为true && 0 === 0

If you want to avoid this, you may change your code to:如果您想避免这种情况,您可以将代码更改为:

return (
  <div>
    {flag1 && flag2 && data1 && data1.length !== 0 && data2 && data2.length !== 0 && (
      <div className="answers-heading">Answers ({data2.length})</div>
    )}
  </div>
);

Put !!放 !! Infront of all numeric values and it will be true if that number exists and is not 0在所有数值的前面,如果该数字存在且不为 0,则为真

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

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