• React报错之Encountered two children with the same key


    正文从这开始~

    总览

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

    react-encountered-two-children-with-the-same-key.png

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

    // 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属性在整个对象中不是独一无二的。

    index

    解决该问题的一种方式是使用索引。它是传递给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属性那样稳定。

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

  • 相关阅读:
    3.Python_创建型模式_抽象工厂模式
    批发/零售商家如何合理控制库存?做好优化库存结构
    SQL的CASE WHEN函数、CAST函数、CONVERT() 函数、COALESCE()函数、DATEDIFF()函数
    谷歌(Chrome)无法进行更新
    13 | 集合中泛型
    【跨境电商】全渠道客户服务终极指南(一):概念,重要性与优势
    SpringMVC的请求处理流程及核心组件
    c++(27)STL:容器、算法、迭代器
    盛会落幕,精彩延续 | 云扩科技入选《2022中国AI商业落地市场研究报告》
    基于人工智能与边缘计算Aidlux的工业表面缺陷检测
  • 原文地址:https://www.cnblogs.com/chuckQu/p/16581398.html