簡體   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