首页 > 解决方案 > React JS 唯一键道具

问题描述

请看一下我的反应组件中的一小部分代码。

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;
  }

为什么这个渲染方法会给出唯一“关键”道具的警告?请注意,ProductRow组件由tr标签组成,每个标签都有唯一的item.id键。所以,里面没问题。

我的数据:

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

标签: reactjskeywarnings

解决方案


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


推荐阅读