Do you mean how to cancel an interval function if the component is already unmounted?
There is such a case that the interval call has already started right before the component is unmounted, if so you can add a flag _mounted
in your class to check if the component is unmounted.
class Timer extends Component{
_mounted = true
timer;
componentDidMount() {
this.timerID = setInterval(
() => {
if (this._mounted) {
this.tick()
}
},
1000
);
}
componentWillUnmount() {
this._mounted = false
window.clearInterval(this.timer)
}
render() {
const { time } = this.state
return time === 0 ? null : (
<div>xxx</div>
);
}
}
export default Timer
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…