首页 > 解决方案 > 反应属性映射问题

问题描述

我正在尝试做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**

我怎样才能解决这个问题?

标签: reactjsreact-reduxrender

解决方案


第一次props.superherosprop值可能是未定义的并且undefined没有map要迭代的属性,所以你必须检查它的类型并且它不是一个数组,你应该为map属性分配一个数组。

尝试使用这种方式:

{(Array.isArray(props.superheros) ? props.superheros : []).map(superhero =>
   <tr key={superhero.name}>
      <td>{superhero.name}</td>
      <td>{superhero.powers}</td>
   </tr>
)}

推荐阅读