reactjs - 反应属性映射问题
问题描述
我正在尝试做React Website的例子,我得到了这个:
function renderSuperheroesTable(props) {
return (
<table className='table'>
<thead>
<tr>
<th>Name</th>
<th>Powers</th>
</tr>
</thead>
<tbody>
{props.superheros.map(superhero =>
<tr key={superhero.name}>
<td>{superhero.name}</td>
<td>{superhero.powers}</td>
</tr>
)}
</tbody>
</table>
);
}
当我跑步时,我收到以下消息:
TypeError: Cannot read property 'map' of undefined
**renderSuperheroesTable**
我怎样才能解决这个问题?
解决方案
第一次props.superheros
prop值可能是未定义的并且undefined
没有map
要迭代的属性,所以你必须检查它的类型并且它不是一个数组,你应该为map
属性分配一个数组。
尝试使用这种方式:
{(Array.isArray(props.superheros) ? props.superheros : []).map(superhero =>
<tr key={superhero.name}>
<td>{superhero.name}</td>
<td>{superhero.powers}</td>
</tr>
)}
推荐阅读
- swift - 如何在更改嵌套数组时重新渲染?
- python - 在 Windows 上获取本地时区名称(Python 3.9 zoneinfo)
- javascript - 从两个现有数组中创建一个新数组,使用 Javascript 按 id 过滤
- node.js - 在 Nodejs/Angular 本地应用程序中使用 Oauth 的 Cors 问题
- python - 如何在 python 中使用 BeautifulSoup 抓取隐藏的表格内容?
- sql - 在 SQL Server Management Studio 中增加数据导出的 MaximumErrorCount
- spring-boot - Eureka Secured Discovery:Eureka 客户端使用端口 0 向 Eureka Server 注册
- python - 整数列用符号分隔的 Python 数据帧分析
- hive - 在 HDP 3.1 集群上执行 flink 1.10 以访问 hive 表
- keras - Mnist Digits 在 25Gb RAM 中崩溃的 FID 分数 Google Colab