import React, { Component } from "react";
class Counter extends Component {
constructor(props) {
super(props);
this.state = { counter: 1 };
}
handleIncrement = () => {
this.setState({ counter: this.state.counter 1 });
};
componentDidUpdate(prevState) {
console.log("prevState", prevState);
}
render() {
return (
<React.Fragment>
<p>{this.state.counter}</p>
<button onClick={this.handleIncrement}>Increment</button>
</React.Fragment>
);
}
}
export default Counter;
I want to access the prevState prop returned from the componentDidMount lifecycle method. However, I get an empty object when I console.log(prevState). Please find attached image of the same. I want the object of the previous state in the console.
Please help me out whether I'm doing something syntactically wrong or it something unexpectedly breaking in the never version of React. I'd love to hear from you.
Thanks!
CodePudding user response:
You have to specify both inputs (prevProps, prevState)
componentDidUpdate(prevProps, prevState) {
console.log("prevState", prevState.counter);
}