I have a class component that doesn't unmount, even though I implemented componentWillUnmount on it. I tried to console.log the mounting phases; it works with the constructor and componentDidUnmount but not componentWillUnmount. Also it gives me an error: Warning: Can't perform a React state update on an unmounted component whenever I open this screen. I'm still a new learner and I don't understand the mounting concept too well.
Here's my code (it doesn't console.log "unmount"):
constructor(props) {
console.log('before');
super(props);
this.state = { doctors: '' };
this.fetchDo = this.fetchDo.bind(this);
}
fetchDo() {
firebase
.firestore()
.collection('Doctors')
.get()
.then((snapshot) => {
let doctorsdata = snapshot.docs.map((doc) => {
const data = doc.data();
const id = doc.id;
return { id, ...data };
});
this.setState({
doctors: doctorsdata,
});
});
}
componentDidMount() {
this.fetchDo();
console.log('mount');
}
componentWillUnmount() {
this.fetchDo();
console.log('unmount');
}
This is maybe because your component is at the root of your navigation stack. It is never unmounted if it stays at the bottom of your stack. Try resetting the stack and you will see the console log.
Here is how you can reset your stack.
import { NavigationActions, StackActions } from 'react-navigation';
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'MainActivity' })],
});
this.props.navigation.dispatch(resetAction);