如何在React Js中超时时删除组件



我试图找出React的方式来删除超时后的组件

我试过这样设置定时器:在设定时间后从DOM中删除元素

下面是我的组件的代码:
import React, {Component} from 'react'
class Timer extends Component{
constructor(props) {
super(props);
this.state = {
time: 2,
date: new Date()};
}

componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);

}
tick() {
this.setState({
date: new Date(),
time: this.state.time - 1 
});
if (this.state.time <= 0) {
clearInterval(this.timerID);
}
}
componentWillUnmount() {
alert("Unmount")
}
render() {
return (
<div>
Now {this.state.date.toLocaleTimeString()}. Count Down {this.state.time}
</div>
);
}
}
export default Timer

您的意思是如果组件已经卸载,如何取消间隔功能?

有这样一种情况,间隔调用已经开始之前的组件卸载,如果是这样,你可以添加一个标志_mounted在你的类来检查组件是否卸载。

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

最新更新