【问题标题】:Each child in an array or iterator should have a unique "key" prop. Not sure why数组或迭代器中的每个孩子都应该有一个唯一的“key”道具。不知道为什么
【发布时间】:2018-10-11 23:31:47
【问题描述】:
const list = props.things.toDo.map(
  function(thing) {
    return(
      <li>{thing.name}</li>
    );
  }
);

想不通继续收到这个反应警告?!

【问题讨论】:

    标签: reactjs react-redux reactive-programming


    【解决方案1】:

    键帮助 React 识别哪些项目已更改、添加或删除。应为数组内的元素赋予键,以赋予元素稳定的身份:

    const numbers = [1, 2, 3, 4, 5];
    const listItems = numbers.map((number) =>
      <li key={number.toString()}>
        {number}
      </li>
    );
    

    选择键的最佳方法是使用一个字符串,该字符串在其兄弟项中唯一标识一个列表项。大多数情况下,您会使用数据中的 ID 作为键:

    const list = props.things.toDo.map(
      function(thing) {
        return(
          <li key={thing.id}>{thing.name}</li>
        );
      }
    );
    

    当您没有用于渲染项目的稳定 ID 时,您可以使用项目索引作为键作为最后的手段:

    const list = props.things.toDo.map(
      function(thing, index) {
        return(
          <li key={index}>{thing.name}</li>
        );
      }
    );
    

    如果项目的顺序可能发生变化,我们不建议对键使用索引。这会对性能产生负面影响,并可能导致组件状态出现问题。如果您选择不为列表项分配显式键,那么 React 将默认使用索引作为键。


    参考https://reactjs.org/docs/lists-and-keys.html#keys

    【讨论】:

      【解决方案2】:

      作为一个快速修复,试试这个:

      <li key={thing.name}>{thing.name}</li>
      

      然后阅读 Lists and Keys 的 React 文档。

      键帮助 React 识别哪些项目已更改、添加或删除。应该为数组内的元素提供键,以使元素具有稳定的标识。

      如果不能保证 thing.name 在各个项目中相同,您可能希望将键替换为真正唯一的值。

      【讨论】:

        【解决方案3】:
        const list = props.things.toDo.map((x, i) => <li key={i}>{thing.name}</li>);
        

        您的代码可以浓缩为上述代码。正如其他人所提到的,每当我们渲染一个列表时,React 将需要每个单独的元素都是唯一的,在这种情况下它需要一个 key 道具,而不是使用 key={thing.name} ,我相信有机会 @ 987654324@ 不是唯一的,我通常会使用索引来代替,它 100% 保证是唯一的

        【讨论】:

          猜你喜欢
          • 2017-02-23
          • 2017-02-03
          • 2018-04-29
          • 2018-05-22
          • 2017-07-28
          • 1970-01-01
          • 2016-10-05
          • 1970-01-01
          相关资源
          最近更新 更多