这是我的代码,除了包含clearInterval的stopTimer方法之外,一切都很好:
componentDidMount() {
this.insertArray();
that = this;
this.setState({
interval: setInterval(function() {
let elapsed_time=(Math.floor(Date.now() / 1000)) - that.state.data;
that.setState({
elapsed: that.secondsToHms(elapsed_time)
});
}, 1000)
});
}
secondsToHms(d){
d = Number(d);
var h = Math.floor(d/3600);
var m = Math.floor(d%3600/60);
var s = Math.floor(d%3600%60);
return ('0' + h).slice(-2) + ":" + ('0' + m).slice(-2) + ":"+ ('0' + s).slice(-2);
}
stopTimer(){
clearInterval(this.state.interval);
}
这就是我调用 stopTimer 方法的方式:
<TouchableOpacity onPress={()=>this.stopTimer()>
<Text>stopTimer</Text>
</TouchableOpacity>
最佳答案
状态不是存储此类引用的正确位置。它并不代表您的观点状态。
由于没有快速干净的方法来执行此操作,因此请在其中保留超时的引用,这是您的组件。它将在 Android 上运行。
this.interval = setInterval(function() {})
另外,不要忘记在触发 componentWillUnmount 时清除。
关于javascript - react native clearInterval在android中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50688052/