简体   繁体   English

为什么 React 条件渲染会渲染 NaN?

[英]Why does React conditional rendering render NaN?

Given value = NaN When value && value > 0 && <Component> .给定value = NaNvalue && value > 0 && <Component>

For some reason, the app renders "NaN" rather than not rendering anything.出于某种原因,该应用程序呈现“NaN”而不是不呈现任何内容。 Am I missing something?我错过了什么吗? I would have thought that because NaN is not greater than 0...it would not render anything?我会认为因为 NaN 不大于 0 ......它不会渲染任何东西?

The logical AND ( && ) expression syntax is: 逻辑 AND ( && )表达式语法为:

expr1 && expr2

According to the documentation:根据文档:

If expr1 can be converted to true , returns expr2 ;如果expr1可以转换为true ,则返回expr2 else, returns expr1 .否则,返回expr1

Because NaN is expr1 and is falsy, NaN is returned.因为NaNexpr1并且是假的,所以返回NaN

If you want the component to render only if value exists and is a number greater than 0, you may be able to simply write:如果您希望组件仅在value存在且大于 0 的数字时呈现,您可以简单地编写:

value > 0 && <Component>

so you basically might give this a shot所以你基本上可以试一试

if value !== NaN {
    if value && value > 0 && <Component> {
       // do something 
    } else {}
} else {}

or chain the entire logic, but personally I'd prefer this for readability或链接整个逻辑,但我个人更喜欢这个以提高可读性

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

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