我正在我的 ReactJS 应用程序中创建一个 setInterval,我需要稍后在组件卸载时清除它。因此,我无法使用我使用的以下代码来实现此目标:
var Timer = React.createClass ({
getInitialState: function () {
return ({
timeLeft: "99:99:99"
})
},
componentDidMount: function () {
var compteur = setInterval( function () {
var heure = new Date();
var timeH = ((0 + this.props.endH - heure.getHours()) > 9) ? (0 + this.props.endH - heure.getHours()) : ("0" + (0 + this.props.endH - heure.getHours())) ;
var timeM = ((0 + this.props.endM - heure.getMinutes()) > 9) ? (0 + this.props.endM - heure.getMinutes()) : ("0" + (0 + this.props.endM - heure.getMinutes())) ;
var timeS = ((0 + this.props.endS - heure.getSeconds()) > 9) ? (0 + this.props.endS - heure.getSeconds()) : ("0" + (0 + this.props.endS - heure.getSeconds())) ;
this.setState({
timeH: timeH,
timeM: timeM,
timeS: timeS
});
this.setState ({
timeLeft: this.state.timeH + ":" + this.state.timeM + ":" + this.state.timeS
})
}.bind(this), 900);
compteur;
},
componentWillUnmount: function () {
console.log("Unmounting Timer...");
clearInterval(this.compteur);
this.compteur = false;
},
render: function() {
return (
<div className="time-count">{this.state.timeLeft}</div>
)
}
});
问题是,当我尝试通过 clearInterval(compteur)
设置间隔后立即清除它时,它起作用了。但当我稍后尝试使用 clearInterval(this.compteur)
执行此操作时,情况并非如此。
谢谢!
最佳答案
当您像这样声明 compteur
时,您是在告诉这是一个范围在 componentDidMount
函数中的普通变量。
直接替换即可
var compteur = setInterval( function () {
与
this.compteus = setInterval( function () {
您将能够从 componentWillUnmount
函数访问 this.compteur
。
工作演示:https://jsfiddle.net/mrlew/bfexkpkx/
关于javascript - 在 ReactJS 中清除 setInterval(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42181361/