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

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

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

// 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方法的第二个参数。

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属性保证是唯一的。

// 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属性那样稳定。

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

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值