reactjs - 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"
}
];
解决方案
将 key={category} 放在片段标签上
推荐阅读
- javascript - 如何在字母表中向上移动一个字符?
- angular - 执行多个请求角度 8
- c# - 通过 C# 删除为 lambda 配置的环境变量
- javascript - 如果括号仅包含属性访问器,是否会忽略括号?
- reactjs - 在 react-bootstrap 中编辑导航栏或其他组件
- asp.net - .NET Core 3.0 中没有注册页面的脚手架标识
- c# - WPF DatagridComboboxcolumn 不是组合框样式
- azure-functions - Azure 功能:无法加载 DLL 认知语音 dll
- powershell - 使用 PowerShell 在没有备用数据流的情况下搜索数据的小问题
- azure - 如何在 Azure 上部署一个 Sping Restfull api