I have React lifecycle method as follows:
componentWillReceiveProps(nextProps){
if(this.props.totalVehicles !== nextProps.totalVehicles){
this.setState({animation: "cartCount"}, () => setTimeout(() => this.setState({animation: null}), 1000));
}
}
But that gives me:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Header component.
How to set state in the lifecycle methods without getting those errors?
Although this is an old questions, i'll answer it for future references.
When using setState
(which is asynchronous) via setTimeout
, you have to remember to clear the timeout on componentWillUnmount
.
Otherwise, you might get to situations in which the setState
is called after the element has already unmounted.
How about setting it on componentWillUpdate
? That way, you know that the component has mounted already. Docs here
If you want to set up initial state, do it in componentWillMount
.
More lifecycle methods in here
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