javascript - 在react native中,使用es6语法怎么清除定时器?

查看:122
本文介绍了javascript - 在react native中,使用es6语法怎么清除定时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我想做一个类似倒计时的效果,当倒计时为0的时候,计时器停止,但是目前不知道怎么做,求大神解答,谢谢!新手求助!
目前有如下代码:

const totalCount = 10;
class Register extends Component {
    ...
     // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            count: totalCount
        };
        this.componentWillUnMount = this.componentWillUnMount.bind(this);
    }

    componentWillUnMount() {
        clearInterval(this.timer);//FIXME:无法实现卸载时清除计时器
    }
    
    count() {
        this.timer = setInterval(()=>this.setState({
                count: this.state.count - 1
            }
        ), 1000);
        if (this.state.count == 0) {
            //clearTimeout(this.timer)//FIXME:确定程序可以走到这里,但是无法实现清除计时器
            clearInterval(this.timer);
        }
    }
    
    render() {
        return(
             ...
             <TouchableOpacity onPress={this.count.bind(this)} disabled={!(this.state.count == totalCount || this.state.count == 0)}>
                            ...
             </TouchableOpacity>
        )
    }
}

解决方案

现在问题已解决:
1、componentWillUnMount() ---> componentWillUnmount()
ps:Unmount的m为小写!

2、和楼上回答一致:

count() {
        this.timer = setInterval(()=> {
            this.setState({
                count: this.state.count - 1
            });
            if (this.state.count == 0) {
                clearInterval(this.timer);
            }
        }, 1000);
    }

这篇关于javascript - 在react native中,使用es6语法怎么清除定时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆