React表格渲染出现唯一key属性缺失警告,求解决方案
Hey there! Let's sort out that key warning you're running into. I checked over your code, and the issue comes down to a small variable name collision in your map function.
The Problem
In your render method, you're using:
{emps.map(emps => <tr key={emps.Id}>
You've named the individual item in the map callback the same as your array (emps), which means inside the callback, emps refers to the single employee object instead of the original array. While this might work for rendering basic data, it's confusing and could lead to unexpected behavior—plus, if the Id isn't being accessed correctly under this naming clash, React won't get the unique key it needs to silence the warning.
The Fix
Just rename the callback parameter to something distinct, like emp, so it doesn't clash with your array name. Here's the corrected full code for your component, with the key fix highlighted:
import React,{Component} from 'react'; import {Table} from 'react-bootstrap'; class EmployeeList extends Component{ constructor(props){ super(props); this.state = {emps:[]} } componentDidMount(){ this.refreshList(); } refreshList(){ fetch('https://localhost:44339/api/employee') .then(response=> response.json()) .then(data => { this.setState({emps:data}) }); } render() { const {emps} = this.state; return( <Table className="mt-4" striped bordered hover size="sm"> <thead> <tr> <th>Id</th> <th>FirstName</th> <th>LastName</th> <th>Email</th> <th>Address</th> </tr> </thead> <tbody> {/* Renamed the callback parameter from `emps` to `emp` */} {emps.map(emp => ( <tr key={emp.Id}> <td>{emp.Id}</td> <td>{emp.FirstName}</td> <td>{emp.LastName}</td> <td>{emp.Email}</td> <td>{emp.Address}</td> </tr> ))} </tbody> </Table> ) } } export default EmployeeList;
A Quick Note on Keys
- Make sure
emp.Idis truly unique across all your employee records (which it should be, since it's an ID field from your API). Unique keys help React efficiently update the list when data changes, as it can track which items have been added, removed, or modified. - Avoid using array indexes (
index) as keys unless your list is completely static (no sorting, adding, or removing items). Indexes can shift when the list changes, which breaks React's diffing algorithm and causes unnecessary re-renders.
That should get rid of the warning and make your component work smoothly!
内容的提问来源于stack exchange,提问作者Meet Parmar

