在React抛出错误中使用Map循环通过数组



我有一个功能组件,它正在从API读取数据。我已经定义了一个接口,但无法使用react中的Map在表中循环和显示。

错误

index.js:1 Warning: Each child in a list should have a unique "key" prop.

接口

export interface ISiteManager{
managerId: number,
name: string,
isDeleted: false
}

React功能组件返回模板

...
return (

<div>
<h2>EziTracker Dashboard Report</h2>
{eziStatusCollection && eziStatusCollection.length >0 && (
<table  className="table">
<thead>
<tr>
<th>ManagerId</th>
<th>Name</th>
<th>Is Deleted</th>
</tr>
</thead>
{
eziStatusCollection.map((item, index) => {
return(
<tbody>
<tr key={index}>
<td>{item.managerId}</td>
<td>{item.name}</td>
<td>{item.isDeleted}</td>
</tr>
</tbody>
)})
}
</table>)}
</div>
);
};
export default MyComponent;

您的表体应该在映射之外,因为它每次都在循环:

<tbody>
{
eziStatusCollection.map((item, index) => {
return(

<tr key={index}>
<td>{item.managerId}</td>
<td>{item.name}</td>
<td>{item.isDeleted}</td>
</tr>
)})
}
</tbody>

通过这种方式,映射键将与每个子项(tr(相关联,并且不应发生错误。

最新更新