ReactJs-列表中的每个孩子都应该有一个唯一的“关键”道具

时间:2019-07-03 09:56:36

标签: javascript c# reactjs api

如何使用实体框架从api中使用ReactJs来获取数据。首先,我生成了模型,然后使方法成为api。之后,我使用js获取api。我看FetchData的示例,当我第一次获得构建项目时。我做的一样,但我的代码无法正常工作。显示错误列表中的每个孩子都应该有一个唯一的“关键”道具。我的代码api或JavaScript有什么问题?

控制器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>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

通过查看错误,我们可以说您的EmployeeId不是唯一的。您必须提供独特的key道具才能列出项目。你可以做到的,

{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>
)}