React JS 独特的关键道具

React JS unique key prop

请看我的 React 组件中的这一小部分代码。

render() {
    // below line makes sure that each category is unique
    const categories = this.getUniqueCategories(this.props.items);
    const TRs = categories.map(category => {
      return (
        <React.Fragment>
          <tr key={category}>
            <td colSpan="2">{category}</td>
          </tr>
          <ProductRow items={this.props.items} category={category} />
        </React.Fragment>
      );
    });
    return TRs;
  }

为什么这个渲染方法给出了独特的 "key" 属性的警告?请注意,ProductRow 组件由 tr 个标签组成,每个标签都有唯一的 item.id 键。所以,那里没问题。

我的数据:

const items = [
      {
        id: "1",
        category: "Sporting Goods",
        price: ".99",
        stocked: true,
        name: "Football"
      },
      {
        id: "2",
        category: "Sporting Goods",
        price: ".99",
        stocked: true,
        name: "Baseball"
      },
      {
        id: "3",
        category: "Sporting Goods",
        price: ".99",
        stocked: false,
        name: "Basketball"
      },
      {
        id: "4",
        category: "Electronics",
        price: ".99",
        stocked: true,
        name: "iPod Touch"
      },
      {
        id: "5",
        category: "Electronics",
        price: "9.99",
        stocked: false,
        name: "iPhone 5"
      },
      {
        id: "6",
        category: "Electronics",
        price: "9.99",
        stocked: true,
        name: "Nexus 7"
      }
    ];

将 key={category} 放在片段标签上