React 属性 地图问题

React property map issue

我正在尝试做 React 网站 的示例,我得到了这个:

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**

我该如何解决这个问题?

好吧,当你在渲染中映射时你必须使用 return,请检查 props.superheros 是否是一个数组并且

{props.superheros?props.superheros.map((element)=>{
  //your code 
 })
 :null  //if undefined it prints nul
 }

第一次 props.superheros prop value 可能未定义并且 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>
    );
}