react-native - setTimeout 将我的应用程序冻结在本机反应中
问题描述
我正在使用 setTimeout 函数来显示 3.. 2.. 1.. 在开始我的实际功能之前先显示文本
但有时应用程序会在 2 或 1 或 GO 处冻结并直接跳转到实际功能。
我的代码如下:
setInterval(() => {
_this.setState({
timer: _this.state.timer - 1
})
if (_this.state.timer == 0) {
_this.setState({ timer: 'GO' })
}
}, 1000)
因此,当计时器为 0 时,每秒都会减少其值,它显示 GO 但我的应用程序正在冻结,谁能帮我解决这个问题谢谢
解决方案
你可以这样使用。因为 setInterval 和 setState 都是异步的。
let timer = this.state.timer
let interval = setInterval( () => {
if(typeof timer === "number"){
timer--;
}
if(timer === 0){ //once the timer goes 0 then it clears interval
clearInterval(interval) //to clear Interval
this.setState({ timer: "Go"})
}else{
this.setState({ timer: timer})
}
}, 1000)
推荐阅读
- java - SIGAR api 抛出 NoClassDefFoundError
- reactjs - ReactJS 在组件中捕获向前按钮按下
- javascript - CSS snap scroll:如何在 div 中间诱导 snap 滚动?
- javascript - 如何将 javascript 数组元素流式传输/发送到 S3 存储桶?
- ruby-on-rails - 两次加入表时的条件
- ionic-framework - 如何在 ionic 4 中实现角度圆形滑块
- r - r 按子组为几列计算所有因子水平的频率
- c# - 通过我的 C# 程序启动命令行应用程序时不显示任何内容
- java - 所有应用内购买将在五分钟内取消并退款(Alpha 测试)
- javascript - SignalR 连接后 JavaScript 未运行