映射数组ES6时考虑空值
Account for null values when mapping an array ES6
这是我成功映射了一个数组。。
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.id
?key
应该是具有唯一值的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>)()}
相关文章:
- Lodash 从值数组中查找数组中的值
- 使用Undercore获取属性值数组
- 选择具有值数组的所有元素的最有效方法
- 使用jquery grep过滤具有值数组的json对象
- 如何使用JQuery将值数组插入到数据库中
- 创建属性值数组,其中属性名称以特定字符串结尾
- 如何在jqueryajax中发布值数组
- 如何在不赋值数组变量的情况下读取数组数据
- Lodash 从与值数组不匹配的数组中获取项目
- 下划线,将对象列表转换为对象值数组
- 将键/值数组中的对象与另一个对象(键/值)进行比较
- 使用Node中的Q promise库对值数组顺序调用/执行相同的函数;并返回带有结果的新数组/集合
- 创建一个计算值数组,该数组绑定到AngularJS中的其他输入
- 将JavaScript对象转换为值数组
- 将选定值数组发送到控制器-MVC
- 将键、值对象转换为仅值数组
- 如何将JSON数组转换为键值数组
- 使用一个键的值数组过滤多个javascript对象
- $scope绑定到空值数组 AngularJs
- 根据另一个值数组过滤一个对象数组,返回一个空列表