这是我成功映射数组..
const faculty = props.faculty;
{(faculty.science_department || []).map(science_dep => (
<div className="row">
<p>{science_dep.name} : {science_dep.start_date}</p>
</div>
))}
但是如果数组是空的呢?如何计算空值/空状态?如何在此地图功能中查看?即:显示
<p>There are no faculty members within this category</p>
答案 0 :(得分:1)
假设您想在JSX语法中执行此操作,那么您可以使用ternary operator:
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>
}
答案 1 :(得分:1)
但是如果数组是空的呢?我如何解释null 值/空状态?如何在此地图功能中查看?即:显示
<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
字段。
答案 2 :(得分:0)
{(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>)()}