React+Ant Design Table设置rowKey后仍报唯一key警告求助
Hey Claire, I see you're stuck with that annoying key warning even after setting rowKey on your Ant Design Table—let's work through this and get it sorted out!
What's Triggering the Warning?
Looking over your code, there are a couple of likely reasons:
- Initial empty data entry: Your initial state has
data: [{},]—this empty object doesn't have adoctorID, so when the Table first renders, it tries to useundefinedas the row key. React doesn't accept undefined as a valid unique key, hence the warning. - Potential invalid/missing
doctorIDin API data: If any doctor object from your API lacks a unique, non-emptydoctorID, that'll also throw the same warning.
Step-by-Step Fixes
1. Clean Up Your Initial State
First, replace the initial data value from [{},] to an empty array. This avoids rendering a row with no valid key on the first load:
this.state = { pageNumber: 1, pageSize: 10, keyWork:"", visible:false, doctorID:"", columns:[/* your existing columns here */], data: [], // Swap [{},] for an empty array };
2. Filter Invalid API Data
Add a filter when processing your API response to exclude any entries without a valid doctorID. This ensures only valid rows make it to your Table:
loadData = () => { axios.get(`http://localhost:80/doctor-admin/src/api/api?action=readDoctorName`,{withCredentials:true}) .then(res => { console.log(res.data); // Filter out entries with missing or empty doctorID const doctors = res.data.filter(doc => doc.doctorID != null && doc.doctorID !== ''); if(doctors.length > 0){ this.setState({ data:doctors }); } }) .catch((error) => { console.log(error) }); }
3. Simplify rowKey (Optional but Cleaner)
Instead of using a function for rowKey, you can directly pass the field name as a string—Ant Design Table supports this shorthand, and it's easier to read:
<Table rowKey="doctorID" columns={columns} dataSource={data} bordered />
4. Add Keys to Custom Column Elements (Bonus)
While this isn't the cause of your current warning, it's good practice to add unique keys to elements inside your column's render function to avoid future warnings:
{title:"Management", dataIndex:"management", key:"management", width:200, render:(text, rowData) =>{ return( <div> <Button key="delete-btn" className="delDoctorButton" onClick={()=>this.delDoctor(rowData.doctorID)} >Delete</Button> <Button key="plan-btn" className="planButton" type="primary"> <Link to={{pathname: "/index/plan", state:{doctorid: rowData.doctorID}}} >Plan</Link> </Button> </div> ) }}
Why This Works
By removing the initial empty row and filtering out invalid API entries, you guarantee every row in the Table has a unique, valid doctorID as its key. React relies on these keys to efficiently track list items, so the warning should vanish once you apply these changes.
内容的提问来源于stack exchange,提问作者Claire

