【问题标题】:Loop through array using Map in React throw error在 React 中使用 Map 循环遍历数组抛出错误
【发布时间】:2020-12-02 11:20:58
【问题描述】:

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

错误

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;

【问题讨论】:

    标签: reactjs react-data-grid


    【解决方案1】:

    你的表格主体应该在地图之外,因为它每次都在循环它:

    <tbody>
         {
            eziStatusCollection.map((item, index) => {
              return(
              
                <tr key={index}>
                  <td>{item.managerId}</td>
                  <td>{item.name}</td>
                  <td>{item.isDeleted}</td>
                </tr>
            )})
          }
      </tbody>
    

    这样映射键将与每个子 (tr) 相关联,并且不应发生错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2010-10-02
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 2021-09-22
      • 2019-02-04
      相关资源
      最近更新 更多