Reputation: 671
React 16.13.1
Newbie.
I add the componentDidUpdate lifecycle method to my component:
export default class MyComponent extends React.Component {
componentDidUpdate(prevProps, prevState) {
console.log('componentDidUpdate');
//this.state
}
render () { ... }
In an onChange handler I update the state and componentDidUpdate
fires. However prevState
enters as null. Also, within the method this.state
is null.
Any ideas on what I'm doing wrong?
Upvotes: 0
Views: 635
Reputation: 1015
prevState
points to the state before the update (props or state changed), so its expected to be null in your case. You can initialize the state if you want:
export default class MyComponent extends React.Component {
state = {} // initialize here
componentDidUpdate(prevProps, prevState) {
console.log('componentDidUpdate');
//this.state
}
render() { ... }
}
Upvotes: 1
Reputation: 15146
Use constructor()
, define the state data structure inside, as well as setting the init value of it.
class YourComponent extends React.Component<Props, State>{
static defaultProps = {
classes: {},
};
constructor(props: Props) {
super(props);
this.state = {
};
}
componentDidUpdate(prevProps, prevState) {
}
...
}
Upvotes: 1