reactjs - “警告:列表中的每个孩子都应该有一个唯一的“key”道具“用于包含数组中“key”属性的对象
问题描述
该组件MyComp
接受一组对象,它将从中构造按钮。我还key
为每个对象提供了一个。在这种情况下,应从 1 元素对象数组创建 1 个 Button:
<MyComp
buttons={[{"key":"approvalsButton","variant":"info","text":"Approvals Queue","url":"/approvals"}]} />
组件定义
export default function MyComp(props) {
return (
<Col lg={6} className="home-tile">
<div className="home-tile-content">
<div className="home-tile-buttons">
{
/* Loop through specified Buttons (if any) and their object attributes */
props.buttons
?
props.buttons.map(button => (
<LinkContainer to={button.url}>
<Button key={button.key} variant={button.variant}>{button.text}</Button>
</LinkContainer>
))
:
''
}
</div>
</div>
</Col>
但我仍然得到
Warning: Each child in a list should have a unique "key" prop.
Check the render method of `MyComp`. See https://reactjs.org/link/warning-keys for more information.
解决方案
正如错误所述,正在渲染的元素map
需要一个key
属性来唯一标识它们。这与您正在使用的对象或它们是否具有名为的属性无关key
,这只是指正在渲染的实际组件。在这种情况下<LinkContainer>
。
在大多数情况下,您不需要使用此属性,但框架会使用。因此,在大多数情况下,您可以简单地使用map
回调的第二个参数,即集合的索引。例如:
props.buttons.map((button, i) => (
<LinkContainer key={i} to={button.url}>
<Button variant={button.variant}>{button.text}</Button>
</LinkContainer>
))
如果您的数组中的对象确实具有独特的属性,那么您也可以轻松地使用它:
props.buttons.map(button => (
<LinkContainer key={button.key} to={button.url}>
<Button variant={button.variant}>{button.text}</Button>
</LinkContainer>
))
推荐阅读
- pandas - 如何使用熊猫查找给定范围内的计数
- python - 如何从纪元获取周数和年份
- java - 在 Java 中表示匿名交集类型
- python - Numpy 数组(追加、连接)
- reactjs - 使用 .map 函数将状态传递给子组件
- python - 无法使用 tensorflow 1.15 保存通用 lite 的 tensorflow hub 模型
- apache-kafka - 无法运行 Kafka 控制台生产者 (NoSuchMethodError)
- sass - 当我尝试使用变量或混合时,使用“@use”规则将部分导入到主 sass 文件中会返回未定义的错误
- algorithm - 如何从表中选择特定值并避免重复?
- c - Tcp 和 udp 最大数据包大小