我是新手,还是会在在线课程中编写代码。我收到警告,清单上的每个孩子都应该有一个独特的钥匙道具。但是,子组件已经具有唯一的键道具。
程序应将对象值的值增加,在这种情况下,当按下增量按钮但我遇到按键错误时,将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;
答案 0 :(得分:0)
用以下内容替换渲染部分:
render() {
const { counters } = this.state;
return (
<div>
{counters.map(counter => {
const counterKey = `counter-${counter.id}`;
return (
<Counter
key={counterKey}
onIncrement={this.handleIncrement}
/>
)})
}
</div>
);
}