繁体   English   中英

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

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

如何使用实体框架从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>
    );
  }
}

通过查看错误,我们可以说您的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>
)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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