简体   繁体   中英

ReactJs - Each child in a list should have a unique “key” prop

How to make lopping using ReactJs from api using Entity Framework to get Data. First, I generated model and then make method api. after that I lopping using js to get api. I look at the example from FetchData, When I get build project the first time. I make the same but my code not working. show the error Each child in a list should have a unique "key" prop. What wrong with my code api or my javascript?

Controller Api

[HttpGet("[action]")]
public IEnumerable<Employees> Employees()
{
  return db.Employees.ToList();
}

public class Employees
{
  public int EmployeeId { get; set; }
  public string EmployeeName { get; set; }
  public DateTime? JoinDate { get; set; }
  public decimal? Height { get; set; }
}

javascript

import React, { Component } from 'react';

export class ListData extends Component {
  constructor(props) {
    super(props);
    this.state = { forecasts: [], loading: true };

    fetch('api/SampleData/Employees')
      .then(response => response.json())
      .then(data => {
        this.setState({ forecasts: data, loading: false });
      });
  }

  static renderForecastsTable(forecasts) {
    return (
      <table className='table table-striped'>
        <thead>
          <tr>
            <th>No</th>
            <th>Name</th>
            <th>Join Date</th>
            <th>Height</th>
          </tr>
        </thead>
        <tbody>
          {forecasts.map(forecast =>
            <tr key={forecast.EmployeeId}>
              <td>{forecast.EmployeeId}</td>
              <td>{forecast.EmployeeName}</td>
              <td>{forecast.JoinDate}</td>
              <td>{forecast.Height}</td>
            </tr>
          )}
        </tbody>
      </table>
    );
  }

  render() {
    let contents = this.state.loading
      ? <p><em>Loading...</em></p>
      : ListData.renderForecastsTable(this.state.forecasts);

    return (
      <div>
        <h2>List</h2>

        <p><a href="#">Create New</a></p>

        {contents}
      </div>
    );
  }
}

By looking at the error, we can say that your EmployeeId is not unique. You must give unique key prop to list items. You can do this,

{forecasts.map((forecast,index) =>
     <tr key={index}> //Don't make it habit to use index as key props, use something unique from your array
         <td>{forecast.EmployeeId}</td>
         <td>{forecast.EmployeeName}</td>
         <td>{forecast.JoinDate}</td>
         <td>{forecast.Height}</td>
     </tr>
)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM