我正在尝试与react的孩子一起进行父母沟通,我传递了三个具有唯一ID的按钮,我想在单击增量按钮后简单地显示值。第一次单击时,每个按钮的确可以递增,但是,第二次单击任何按钮后,
无法读取未定义的属性“值”
。我不确定第一次单击后会发生什么。
let data = [
{id: 1, value: 85},
{id: 2, value: 0},
{id: 3, value: 0}
]
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 1,
data: this.props.data
}
}
componentWillReceiveProps(nextProps) {
if(nextProps !== this.state.data) {
this.setState({data: nextProps})
}
}
handleClick(id) {
this.props.increment(id,
this.state.data[id-1].value = this.state.data[id-1].value +
this.state.counter);
}
render() {
return (
<div>
{data.map(data => {
return (
<div key={data.id}>
{data.value}
<button onClick={() => this.handleClick(data.id)}>+</button>
</div>
)
})}
</div>
)
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
data
}
}
onIncrement(id, newValue) {
this.setState((state) => ({
data: state.data[id-1].value = newValue
}))
}
render() {
return (
<div>
<Counter data={this.state.data} increment={this.onIncrement.bind(this)}/>
</div>
)
}
}
ReactDOM.render(
<App />,
document.querySelector("#root")
)
import React from 'react';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 1,
data: this.props.data
};
}
handleClick(id, index) {
this.props.increment(
id,
(this.props.data[id - 1].value =
this.props.data[id - 1].value + this.state.counter), index
);
}
render() {
return (
<div>
{this.props.data.map((data
, index) => {
return (
<div key={data.id}>
{data.value}
<button onClick={() => this.handleClick(data.id, index)}>+</button>
</div>
);
})}
</div>
);
}
}
export default class App extends React.Component {
constructor() {
super();
this.state = {
data: [{ id: 1, value: 85 }, { id: 2, value: 0 }, { id: 3, value: 0 }]
};
}
onIncrement(id, newValue, index) {
let {data} = this.state;
data[index].value = newValue;
this.setState({
data
});
}
render() {
console.log(this.state.data)
return (
<div>
<Counter
data={this.state.data}
increment={this.onIncrement.bind(this)}
/>
</div>
);
}
}
请看看您是否以错误的方式进行状态更新
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句