简体   繁体   中英

How to fix a conditional problem in react

I am using a condition such that if activeCardId is null nothing returns otherwise it would return something.It is working fine for all values except 0. It is returning nothing when value is 0.

I think it's related to 0 and null.

constructor(props) {
  this.state = {
    activeCardId: null 
  }
}

return(
  {this.state.activeCardId && ( // some random output...)

As this statement means if activecardId is not null then return some random output and return nothing if activecardId is null.

It's because, you are using logical AND (&&) .

0 means falsy value, and logical AND dosen't return anything for false values, you should try this

{this.state.activeCardId !==null && ( // some random output...) }

0 is a falsy value so

this.state.activeCardId

becomes false

this would do the job:

return(
      {this.state.activeCardId!==null && ( // some random output...)

there is difference between null and 0, 0 is a value, 0 is also falsy in boolean statement while null represents the intentional absence of any object value.

taken from: MDN Null-javascript

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