在React中,我有一个用于更改状态对象属性值的按钮,称为1。由于某些原因,我单击按钮后,其他状态值(状态对象属性值2和3)将消失。 当我console.log它说未定义。 有帮助吗?
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state = {
numbers:{
one:1,
two:2,
three:3
},
};
}
decrement = () => {
this.setState(prevState => {
return {
numbers:{
one: prevState.numbers.one - 1
}
}
}, () => console.log(
this.state.numbers.one,
this.state.numbers.two,
this.state.numbers.three
));
}
render() {
return (
<div className="App">
<div>{this.state.numbers.one}</div>
<div>{this.state.numbers.two}</div>
<div>{this.state.numbers.three}</div>
<br/>
<button onClick={this.decrement}>ok</button>
</div>
);
}
}
export default App;
答案 0 :(得分:3)
设置状态时要替换数字对象,而应该克隆它
this.setState(prevState => {
return {
numbers:{
...prevState.number,
one: prevState.numbers.one - 1
}
}
}, () => console.log(
this.state.numbers.one,
this.state.numbers.two,
this.state.numbers.three
));