javascript - 在react native中,使用es6语法怎么清除定时器?
PHP中文网
PHP中文网 2017-04-11 13:13:22
[JavaScript讨论组]

我想做一个类似倒计时的效果,当倒计时为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(
             ...
             
                            ...
             
        )
    }
}
PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(2)
迷茫

现在问题已解决:
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);
    }
大家讲道理

把这一句 if (this.state.count == 0) {

        clearInterval(this.timer);
    }
    
   放在定时执行函数体内
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号