React列表子元素需唯一key警告:已设唯一_id仍报错
我在React项目中给列表项设置了唯一的_id作为key属性,但依然收到「Each child in a list should have a unique 'key' prop」警告,报错指向QuestionsDetails组件的渲染方法。
相关数据结构
var questionsList = [{ _id: '1', upVotes: 3, downVotes: 2, noOfAnswers: 2, questionTitle:"What Is Function Hmm?", questionBody:"It Meant To Be", questionTags:["javascript", "r", "python"], userPosted: "mano", userId: 1, askedOn:"jan 1", answer: [{ answerBody: "Answer", userAnswered: "kumar", answerOn: "jan 2", userId: 2, }] },{ _id: '2', upVotes: 3, downVotes:2, noOfAnswers: 0, questionTitle:"What Is Function In JS?", questionBody:"It Meant To Be", questionTags:["javascript", "python"], userPosted: "lano", userId: 1, askedOn:"jan 1", answer: [{ answerBody: "Answer", userAnswered: "kumar", answerOn: " jan 2", userId: 2, }] },{ _id: '3', upVotes: 1, downVotes:0, noOfAnswers: 1, questionTitle:"How To Use A Function?", questionBody:"By Adding Const", questionTags:["javascript", "r", "python", "Css"], userPosted: "mano", userId: 1, askedOn:"jan 2", answer: [{ answerBody: "Answer", userAnswered: "kumar", answerOn: " jan 2", userId:2, }] }]
错误详情
Warning: Each child in a list should have a unique "key" prop.
Check the render method ofQuestionsDetails.
at div
at QuestionsDetails (http://localhost:3000/static/js/bundle.js:2904:66)
at div
at div
at DisplayQuestions
at Routes (http://localhost:3000/static/js/bundle.js:42928:5)
at AllRoutes
at Router (http://localhost:3000/static/js/bundle.js:42861:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:41670:5)
at div
at App
排查方向与解决方法
检查
QuestionsDetails内部的子列表:
你给外层问题列表加了key,但每个问题里的answer数组也是列表,渲染这些回答项时同样需要设置唯一key。比如渲染回答的地方要加:{question.answer.map(ans => ( <div key={ans.userId}> {/* 或结合时间戳等生成更唯一的标识 */} {ans.answerBody} </div> ))}确认外层
key的位置:
确保key直接绑定在QuestionsDetails组件上,而不是它的父容器div。正确写法:{questionsList.map(q => ( <QuestionsDetails key={q._id} question={q} /> ))}错误写法(key加在父div上会导致
QuestionsDetails仍无key):{questionsList.map(q => ( <div key={q._id}> <QuestionsDetails question={q} /> </div> ))}排查隐性重复key:
虽然给定的_id是唯一的,但如果实际接口返回数据存在重复_id,也会触发警告。可以在渲染前打印questionsList确认每个项的_id唯一性。
内容的提问来源于stack exchange,提问作者yash lohade

