简体   繁体   English

在使用 map 循环通过 arrays 时返回 null 而不是 JSX

[英]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 .我正在使用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遍历数组,如果air_date不是nullnull则返回 JSX。

 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 ).我从未见过有人这样做(返回null而不是JSX )。 Is it recommended in react?在反应中推荐吗? I don't want to use a for loop.我不想使用for循环。

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.如果您有条件或可选组件,则返回null表示“无组件”或“无 JSX”是 go 的方式。

In addition, as @k-wasilweski says, using a .map to convert an array into a series of components is standard practice in React.此外,正如@k-wasilweski 所说,使用.map将数组转换为一系列组件是 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.如果你不喜欢返回空值的想法,你可以在最后添加一个.filter(c => c !== null) ,但这真的没有必要。

Thats quite okay, but in React its more common to do it using the ternary operator:没关系,但在 React 中更常见的是使用三元运算符:

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:就像下面评论中提到的@devserkan 一样,您甚至可以这样做:

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

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

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