当作为 props 的一部分传递给自定义 React 组件时,为什么 `index` 不符合唯一键的条件?

Why doesn't `index` qualify as a unique key, when passed as part of props to a custom react component?

当我直接列出项目时,使用 index 是可行的。如下。

        <ol className="item-list">
            {
                props.items.map((item, index) => (
                    <li key={index}>{item}</li>
                ))
            }
        </ol>

但是当我创建一个自定义组件来表示列表项时,使用 index 似乎不符合唯一性......我最终收到警告,如下所示。

        <ol className="item-list">
            {
                props.items.map((item, index) => (
                    <ShoppingItem
                        index={index}
                        item={item}
                    />
                ))
            }
        </ol>

ShoppingItem是一个简单的组件,如下所示。

        const ShoppingItem = props => (
            <li key={props.index}>{props.item}</li>
        );

我在控制台中收到的警告如下。

Warning: Each child in a list should have a unique "key" prop.

您应该仔细阅读 Lists and Keys: Extracting components with keys 的 React 文档。关键在被映射的组件上,而不是它呈现的组件上。

不正确

const ShoppingItem = props => (
  <li key={props.index}>{props.item}</li>
);

<ol className="item-list">
  {
    props.items.map((item, index) => (
      <ShoppingItem
        index={index}
        item={item}
      />
    ))
  }
</ol>

正确

<ol className="item-list">
  {
    props.items.map((item, index) => (
      <ShoppingItem
        key={index} // <-- key goes here
        item={item}
      />
    ))
  }
</ol>