You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React列表渲染出现唯一key属性警告,请求解决方法

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)

解决步骤

  1. 添加唯一key属性:在渲染的PlantItem组件上加上key={id},用每个植物项的id作为key(id是数据自带的唯一标识,符合React对key的要求)。
  2. 修正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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:25:42