首页 > 解决方案 > 数组或迭代器中的每个孩子都应该有一个唯一的“key”道具。不知道为什么

问题描述

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

无法解决这个问题,继续收到这个反应警告?!

标签: reactjsreact-reduxreactive-programming

解决方案


键帮助 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


推荐阅读