问题描述
我正在尝试做反应网站的示例,我明白了:
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
属性值可能是未定义的,并且undefined
没有要迭代的map
属性,因此您必须检查它的类型并且它不是数组,所以应该为map
属性分配一个数组。
尝试使用这种方式:
{(Array.isArray(props.superheros) ? props.superheros : []).map(superhero =>
<tr key={superhero.name}>
<td>{superhero.name}</td>
<td>{superhero.powers}</td>
</tr>
)}
,
您可以先检查数组的长度,然后使用map对其进行迭代:
function renderSuperheroesTable({ superheroes }) {
return (
<table className='table'>
<thead>
<tr>
<th>Name</th>
<th>Powers</th>
</tr>
</thead>
<tbody>
{superheros.length > 0 && superheros.map(superhero =>
<tr key={superhero.name}>
<td>{superhero.name}</td>
<td>{superhero.powers}</td>
</tr>
)}
</tbody>
</table>
);
}
,
在渲染中映射时,您必须使用return,请检查props.superheros是否为数组和
and_then