映射数组ES6时考虑空值

Account for null values when mapping an array ES6

本文关键字:空值 数组 ES6 映射      更新时间:2023-09-26

这是我成功映射了一个数组。。

const faculty = props.faculty;
{(faculty.science_department || []).map(science_dep => (
    <div className="row">
        <p>{science_dep.name} : {science_dep.start_date}</p>
    </div>
))}

但是如果数组是空的呢?如何解释空值/空状态?如何在此地图功能内进行检查?Ie:显示

<p>There are no faculty members within this category</p>

但是如果数组是空的呢?我如何解释null值/空状态?如何在此地图功能内进行检查?Ie:显示

<p>There are no faculty members within this category</p>

考虑到这些要求,我将首先过滤数组,然后如果它包含任何内容,则使用映射来渲染它,否则将渲染占位符消息:

const {faculty} = this.props;
const science_department = (faculty.science_department || []).filter(dep => !!dep);
{ 
    science_department.length ? science_department.map(science_dep => (
        <div className="row" key={warning.id}>
            <p>{science_dep.name} : {science_dep.start_date}</p>
        </div>)
    : 
        <p>There are no faculty members within this category</p> 
}

PS:什么是warning.idkey应该是具有唯一值的science_dep的字段。

假设您想在JSX语法中执行此操作,那么您可以使用三元运算符:

const faculty = props.faculty;
{
  faculty.science_department.length !== 0 ?    
    faculty.science_department.map(science_dep => (
      <div className="row" key={warning.id}>
        <p>{science_dep.name} : {science_dep.start_date}</p>
      </div>
    ))
  :
    <p>There are no faculty members within this category</p>
}
{(faculty.science_department || []).length ? faculty.science_department.map(science_dep => (
<div className="row" key={warning.id}>
    <p>{science_dep.name} : {science_dep.start_date}</p>
</div>
)) : (science_dep => (
<div className="row" key={warning.id}>
    <p>There are no faculty members within this category</p>
</div>)()}