I would like to know how to manage state property when the component mounts and unmounts
.
I have a lot of different components in my application to maintain the application flow. I know about function componentdidmount
and componentWillUnmount
. and I also tried the solution about _isMounted=true
on componentdidmount
function and check _isMounted
properties value when I update setState
and then update _isMounted=false
on componentWillUnmount
function.
but this won't work when more two components come in the picture.
For example following links:
- https://www.robinwieruch.de/react-warning-cant-call-setstate-on-an-unmounted-component/
- Is there a way to check if the react component is unmounted?
as per the example, I have made a common class which will update the value of a component in setMounted
function and will return value in getMounted
function to validate component is mounted or not. These methods work correctly on a single screen when I call another screen from a stack and update some values then comes back on the previous page and refresh page it will ismount=false
.
class Mount {
isMounted=false;
getMounted=()=>{
return isMounted;
}
setMounted=mounted=>{
isMounted=mounted;
}
}
var mount=new Mount();
export default mount;
class example extends component{
componentDidMount=async()=>{
mount.setMounted(true);
await this.loadScreen();
this.willFocusSubscription = this.props.navigation.addListener(
'willFocus',
async() => {
await this.loadScreen();
}
);
}
loadScreen=async()=>{
//some other stuff
if(mount.getMounted()){//second time value is false
this.setState({value:'value'});
}
}
componentWillUnmount() {
mount.setMounted(false);
}
//renderview where i call example2 on buttonclick
}
class example2 extends component{
componentDidMount=async()=>{
mount.setMounted(true);
await this.loadScreen();
}
loadScreen=async()=>{
//some other stuff
if(mount.getMounted()){
this.setState({value:'value'});
this.props.navigation.goBack();
}
}
componentWillUnmount() {
mount.setMounted(false);
this.willFocusSubscription.remove();
}
}
It was showing following warning before using mount functions: Can't perform a React state update on an unmounted component