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

React中使用array.map传key仍报唯一key prop警告问题

如何消除React列表的key属性警告

我正在尝试消除React的警告。我的数据对象数组结构如下:

{
  table: 10,
  roundScores: [9, 2, 3, 4, null, null, null, null, null, null],
  isPlaying: true,
  total: 18,
  key: 10,
}

我通过filter和map渲染Scoreline组件列表:

return tableScores
  .filter((score) => score.isPlaying || round === 1)
  .map((score) => (
    <Scoreline
      key={score.key}
      score={score.roundScores[round - 1]}
      table={score.table}
      round={round}
      total={score.total}
      setScore={setScore}
    />
  ));

但一直收到如下警告:

Warning: Each child in a list should have a unique "key" prop.

我本以为传递key属性能解决问题,但没用。我试过移除filter调用、把map结果存变量后返回、用Fragment包裹Scoreline并在Fragment上设key,都没解决。

完整的tableScores结构:

0: {table: 1, roundScores: Array(10), isPlaying: true, total: 29, key: 1}
1: {table: 2, roundScores: Array(10), isPlaying: false, total: 0, key: 2}
2: {table: 3, roundScores: Array(10), isPlaying: true, total: 18, key: 3}
3: {table: 4, roundScores: Array(10), isPlaying: true, total: 18, key: 4}
4: {table: 5, roundScores: Array(10), isPlaying: true, total: 18, key: 5}
5: {table: 6, roundScores: Array(10), isPlaying: true, total: 18, key: 6}
6: {table: 7, roundScores: Array(10), isPlaying: true, total: 18, key: 7}
7: {table: 8, roundScores: Array(10), isPlaying: true, total: 18, key: 8}
8: {table: 9, roundScores: Array(10), isPlaying: true, total: 18, key: 9}
9: {table: 10, roundScores: Array(10), isPlaying: true, total: 18, key: 10}

解决思路

1. 检查Scoreline组件内部的列表渲染

很多时候这种警告不是来自外层的map,而是Scoreline组件自己内部渲染了子列表却没加key。打开Scoreline的代码,看看有没有用map生成元素的地方,确保每个子元素都设置了唯一的key。

2. 验证过滤后数组的key唯一性

虽然你提供的完整数据里key都是唯一的,但过滤后的数组可能出现重复?可以在代码里加个日志确认:

const filteredScores = tableScores.filter((score) => score.isPlaying || round === 1);
console.log('过滤后的key列表:', filteredScores.map(s => s.key));

如果输出里有重复值,说明数据中存在重复key的对象,得先修复数据。

3. 换个字段作为key,避免用key做数据属性名

React的key是特殊属性,建议不要把它作为数据对象的字段名,容易导致内部处理冲突。把数据里的key改成id,然后用key={score.id}传递:

.map((score) => (
  <Scoreline
    key={score.id}
    score={score.roundScores[round - 1]}
    table={score.table}
    round={round}
    total={score.total}
    setScore={setScore}
  />
));

4. 直接用table字段作为key备选

既然你的table值都是唯一的,完全可以用它来当key,比用key字段更稳妥:

.map((score) => (
  <Scoreline
    key={score.table}
    // 其他props保持不变
  />
));

内容的提问来源于stack exchange,提问作者Brent Bollmeier

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:52:49