In React i have a button that changes state object property value called one. For some reason after i click button, other state values(state object propery value two and three) will disappear. When i console.log it says undefined. Any help?
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;
you are replacing the numbers object when setting the state and you should clone it instead
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
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With