简体   繁体   中英

Returning null instead of a JSX when looping through arrays in react using map

I am looping through an array of objects in react using array.map . The array takes the form:

const seasons = [
             {air_date: null, episode_count: 6},
             {air_date: "2020-02-02", episode_count: 6}
           ]

I am looping through the array using seasons.map , returning JSX if air_date is not null and null otherwise.

 seasons.map((season, index) => {
      if(season.air_date){
         return <span key = {season.id}> {season.episode_count} </span>
     }else{
        return null; // Is this recommended?
    }  
})

I have never seen anyone do this (returning null instead of JSX ). Is it recommended in react? I don't want to use a for loop.

Yes, this is recommended.

If you have a conditional or optional component then returning null to mean "no component" or "no JSX" is the way to go.

In addition, as @k-wasilweski says, using a .map to convert an array into a series of components is standard practice in React.

If you don't like the idea of returning nulls, you could always add a .filter(c => c !== null) at the end, but it's really unnecessary.

Thats quite okay, but in React its more common to do it using the ternary operator:

seasons.map((season, index) =>
  season.air_date ? <span key={season.id}> {season.episode_count} </span> : null
);

And like @devserkan mentioned in the comment below, you can even just do:

seasons.map((season, index) =>
  season.air_date && <span key={season.id}> {season.episode_count} </span>
);

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