react封装倒计时定时器

准备工作:

1.在state中定义倒计时时间;

constructor(props){
    super(props);
    this.state={
        time: 60, 
    }
}

2.添加定时器方法;

// 倒计时
time = () => {
    // 清除可能存在的定时器
    clearInterval(this.timer)
    // 创建(重新赋值)定时器
    this.timer = setInterval(()=>{
        // 当前时间回显-1
        this.setState({
            time:this.state.time-1
        },()=>{
            // 判断修改后时间是否小于1达到最小时间
            if(this.state.time <= 0){
                // 清除定时器
                clearInterval(this.timer)
                // 结束定时器循环
                return
            }
            // 循环自调用
            this.time()
        })
    },1000)
}

3.在组件卸载时清除定时器

componentWillUnmount(){
    clearInterval(this.timer)
}

使用:

在需要使用的地方直接调用time方法即可;

ps:页面加载完成后调用案例如下

componentDidMount(){
    this.time()
}

猜你喜欢

转载自blog.csdn.net/Beamon__/article/details/82286765