简体   繁体   中英

Why does React conditional rendering render NaN?

Given value = NaN When value && value > 0 && <Component> .

For some reason, the app renders "NaN" rather than not rendering anything. Am I missing something? I would have thought that because NaN is not greater than 0...it would not render anything?

The logical AND ( && ) expression syntax is:

expr1 && expr2

According to the documentation:

If expr1 can be converted to true , returns expr2 ; else, returns expr1 .

Because NaN is expr1 and is falsy, NaN is returned.

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 && <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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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