React列表渲染出现唯一key属性警告,请求解决方法
问题描述
我是React新手,在ShoppingList组件里用map遍历plantList渲染PlantItem组件,功能能正常运行,但控制台弹出警告:「列表中的每个子元素都需要唯一的'key'属性」。
相关代码(ShoppingList.js):
function ShoppingList() { return ( <ul className="lmj-plant-list"> {plantList.map(({ id, cover, title, description }) => ( <PlantItem to={"/logement/" + plantList.id + "/#"} id={id} title={title} cover={cover} description={description} /> ))} </ul> ); }
控制台报错信息:
Warning: Each child in a list should have a unique "key" prop.
Check the render method of
ShoppingList.
at div
at ShoppingList
at div
at App
at RenderedRoute (http://localhost:3000/static/js/bundle.js:39974:5)
at Routes (http://localhost:3000/static/js/bundle.js:40397:5)
at Router (http://localhost:3000/static/js/bundle.js:40335:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:38682:5)
解决步骤
- 添加唯一key属性:在渲染的
PlantItem组件上加上key={id},用每个植物项的id作为key(id是数据自带的唯一标识,符合React对key的要求)。 - 修正to属性的错误:原代码里
to={"/logement/" + plantList.id + "/#"}写错了——plantList是整个数组,没有id属性,应该用解构出来的当前项的id,改成to={"/logement/" + id + "/#"}。
修改后的完整代码:
function ShoppingList() { return ( <ul className="lmj-plant-list"> {plantList.map(({ id, cover, title, description }) => ( <PlantItem key={id} to={"/logement/" + id + "/#"} id={id} title={title} cover={cover} description={description} /> ))} </ul> ); }
补充说明
React要求列表渲染时给每个子元素加唯一key,是为了让React能准确追踪每个元素的变化,提升渲染效率,避免DOM不必要的重绘。key必须在当前列表范围内唯一,优先用数据自带的唯一标识(比如id),不要用数组index当key(除非列表不会有增删、排序操作)。
内容的提问来源于stack exchange,提问作者Ricky La Rixe

