React JS独特的按键道具

时间:2018-07-27 21:10:23

标签: reactjs key warnings

请看一下我的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;
  }

为什么此render方法会给出独特的“关键”道具警告?请注意,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"
      }
    ];

1 个答案:

答案 0 :(得分:2)

在片段标签上放置键= {category}