reactjs - 为什么我会收到一条警告说“列表中的每个孩子都应该有一个唯一的 key prop”,但我已经有一个子组件的唯一 key prop
问题描述
我对在线课程做出反应并编写代码是新手。我收到一个警告,列表中的每个孩子都应该有一个唯一的关键道具。然而,子组件已经有一个唯一的 key prop。
当按下增量按钮时,程序应该增加一个对象值的值,在这种情况下 counter.value 加一,但我得到一个键错误。
我尝试将 (argument, index) 添加到我正在使用的 map 函数中,但我收到一个错误,即未定义子组件。
//Parent Component
import React, { Component } from "react";
import Counter from "./counter";
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 9 },
]
};
handleIncrement = counter => {
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = { ...counters };
counters[index].value++;
this.setState({ counters });
};
render() {
return (
<div>
{this.state.counters.map(counter => (
<Counter
key={counter.id}
onIncrement={this.handleIncrement}
/>
))}
</div>
);
}
}
export default Counters;
//Child Component
import React, { Component } from "react";
class Counter extends Component {
return (
<div>
<button
onClick={() => this.props.onIncrement(this.props.counter)}
>
Increment
</button>
}
export default Counter;
解决方案
将渲染部分替换为:
render() {
const { counters } = this.state;
return (
<div>
{counters.map(counter => {
const counterKey = `counter-${counter.id}`;
return (
<Counter
key={counterKey}
onIncrement={this.handleIncrement}
/>
)})
}
</div>
);
}
推荐阅读
- swift - 如何从一个部分删除一行并同时将其添加到另一个部分?
- javascript - Tampermonkey上是否可以通过JavaScript获取百度OCR访问令牌?
- java - 如何更改 dconf 目录?
- azure-devops - ADO gulp 任务 - 将前一个任务的输出变量作为参数传递
- angular - 如何从角度的rest api响应中提取子对象
- python - python 中的数据扩充错误:TypeError: pic 应该是 PIL Image 或 ndarray。得到
- apache-spark - 使用字典创建函数以将列从字符串更改为整数
- javascript - 如何使用material-ui AutoComplete使用从列表中选择键过滤表并手动输入值
- apache-nifi - 如何在 Apache NiFi 中添加或安装补丁
- amazon-web-services - AWS 负载均衡器 DNS 工作正常,但未通过运行状况检查