我需要一个倒数倒数计时器,它以秒为单位,以天,小时,分钟,秒和毫秒(最多两位数,零到100毫秒)的形式返回。
由于延迟,下面的代码有时差。另外,10毫秒占用大量CPU来调用定时器,可能是什么原因造成的呢?
componentDidMount(){
// get the timer in second then timer * 100
this.interval = setInterval(() => {
if (this.state.timer > 0){
this.setState((prevState)=>({
timer: prevState.timer -= 1,
h: Math.floor(this.state.timer / 360000),
m: Math.floor((this.state.timer % 360000) / 6000),
s: Math.floor(((this.state.timer % 360000) % 6000) / 100) ,
mili:Math.floor(((this.state.timer % 360000) % 6000) % 100)
}));
}else{
clearInterval(this.interval)
}
},10);
}
componentWillUnmount(){
clearInterval(this.interval)
}
如果您能提供更多信息,我可以给您更好的评论。
但是在我自己的项目中,我创建了一个TimerCountdown.js文件并在其中编写了下面的代码:
import React, { Component } from 'react';
import { View } from 'react-native';
import { RText } from '../../shared';
class TimerCountdown extends Component {
constructor(props) {
super(props);
this.state ={
timer: props.initialTime
}
}
componentDidMount(){
this.interval = setInterval(
() => this.setState((prevState)=> ({ timer: prevState.timer - 1 })),
1000
);
}
componentDidUpdate(){
if(this.state.timer === 1){
console.log("-------------------timer count down is leaking")
clearInterval(this.interval);
this.props.onTimerElapsed()
}
}
componentWillUnmount(){
clearInterval(this.interval);
this.props.onTimerElapsed()
}
render() {
return (
<Text style={this.props.style}> {this.state.timer} </Text>
)
}
}
export default TimerCountdown;
工作正常并且根本没有泄漏(技巧只是使这个组件成为一个单独的文件,所以当它更新时,它不会影响项目的其余部分)。
我在项目的其他js文件中使用了如下组件:
<TimerCountdown initialTime={60}/>
你可以在qazxsw poi上应用你想要的配置,并从中获得你想要的结果。
希望它对你有所帮助。