为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3146593 2018-09-13 09:25:21
我想做一个类似倒计时的效果,当倒计时为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 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

现在问题已解决:
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);
    }


查看完整回答
反对 回复 2018-10-17
  • 1 回答
  • 0 关注
  • 1307 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号