解决React报错Encountered two children with the same key

当我们从map()方法返回的两个或两个以上的元素具有相同的key属性时,会产生"Encountered two children with the same key"错误。为了解决该错误,为每个元素的key属性提供独一无二的值,或者使用索引参数。

这里有个例子来展示错误是如何发生的。

javascript 复制代码
// App.js
const App = () => {
  // 👇️ name property is not a unique identifier
  const people = [
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
    {id: 3, name: 'Alice'},
  ];
  /**
   * ⛔️ Encountered two children with the same key, `Alice`.
   *  Keys should be unique so that components maintain their identity across updates.
   *  Non-unique keys may cause children to be duplicated and/or omitted --- the behavior is unsupported and could change in a future version.
   */
  return (
    <div>
      {people.map(person => {
        return (
          <div key={person.name}>
            <h2>{person.id}</h2>
            <h2>{person.name}</h2>
          </div>
        );
      })}
    </div>
  );
};
export default App;

上述代码片段的问题在于,我们在每个对象上使用name属性作为key属性,但是name属性在整个对象中不是独一无二的。

解决该问题的一种方式是使用索引。它是传递给map方法的第二个参数。

javascript 复制代码
const App = () => {
  const people = [
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
    {id: 3, name: 'Alice'},
  ];
  // 👇️ now using index for key
  return (
    <div>
      {people.map((person, index) => {
        return (
          <div key={index}>
            <h2>{person.id}</h2>
            <h2>{person.name}</h2>
          </div>
        );
      })}
    </div>
  );
};
export default App;

我们传递给Array.map方法的函数被调用,其中包含了数组中的每个元素和正在处理的当前元素的索引。

索引保证是唯一的,但是用它来做key属性并不是一个最好的做法。因为它不稳定,在渲染期间会发生变化。

更好的解决方案是,使用一个能唯一标识数组中每个元素的值。

在上面的例子中,我们可以使用对象上的id属性,因为每个id属性保证是唯一的。

javascript 复制代码
// App.js
const App = () => {
  const people = [
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
    {id: 3, name: 'Alice'},
  ];
  // ✅ now using the id for the key prop
  return (
    <div>
      {people.map(person => {
        return (
          <div key={person.id}>
            <h2>{person.id}</h2>
            <h2>{person.name}</h2>
          </div>
        );
      })}
    </div>
  );
};
export default App;

使用id作为key属性好多了。因为我们保证了对象id属性为1时,name属性总是等于Alice

React使用我们传递给key属性的值是出于性能方面的考虑,以确保它只更新在渲染期间变化的列表元素。

当数组中每个元素都拥有独一无二的key时,React会更容易确定哪些列表元素发生了变化。

你可以使用index作为key属性。然而,这可能会导致React在幕后做更多的工作,而不是像独一无二的id属性那样稳定。

尽管如此,除非你在渲染有成千上万个元素的数组,否则你很有可能不会注意到使用索引和唯一标识符之间有什么区别。

相关推荐
wyhwust5 小时前
基于Apifox的接口管理工具
前端
柒和远方6 小时前
后端认证、鉴权、高并发:从 Session 到 JWT 再到 Redis
前端·后端·面试
piglet121386 小时前
把搜索调到 Claude.ai 的水准
前端·人工智能
前端Hardy6 小时前
前端圈沸腾!这个动画库月下载超 3000 万次,已经快成行业标准了
前端
文阿花6 小时前
Echarts实现自动旋转柱状3D扇形图
前端·3d·echarts
sp426 小时前
使用 Vite 与 NativeScript
前端
前端Hardy6 小时前
GitHub 爆火!Three.js + React + ECharts 打造最强数据大屏
前端·javascript
如果超人不会飞6 小时前
TinyRobot AI 对话组件库全组件使用指南
前端·vue.js
lichenyang4536 小时前
ArkTS 资源与暗色模式:为什么我手机切暗色,App 内容区却不变
前端
老王以为6 小时前
Claude Code 的产品哲学:当价值观成为架构
前端·claude·vibecoding