react中实现倒计时功能

作者: MJ 分类: react 发布时间: 2019-05-17 21:51

react中实现根据接口返回的毫秒数,显示倒计时:还剩于00分00秒

这里边有几个注意点,详情请查看:用setTimeout()方法来替换setInterval()

import React,{ Component } from 'react';
class OrderDetail extends Component{
    constructor(props){
        super(props)
        this.state={
            msg:""
        }
    }
    timeTransition = (ms) => {
        let maxtime = ms / 1000; //按秒计算
        let timer = null;
        let _this = this;
        setTimeout(function f(){
            if (maxtime >= 0) {
                let minutes = Math.floor(maxtime / 60);
                let seconds = Math.floor(maxtime % 60);
                minutes < 10 ? minutes = '0' + minutes : minutes = minutes;
                seconds < 10 ? seconds = '0' + seconds : seconds = seconds;
                let msg = "请在 <em>" + minutes + "分" + seconds + "秒</em> 内完成支付";
                _this.setState({
                    msg
                });
                --maxtime;
            } else{
                _this.setState({
                    msg:'订单已过期,请重新下单'
                });
                clearTimeout(timer);
                return;
            }
            timer = setTimeout(f,1000);
        },1000);
    }
    componentDidMount(){
        this.timeTransition(20000);//根据接口返回的时间
    }
}
export default OrderDetail;

欢迎关注小程序,感谢您的支持!

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

邮箱地址不会被公开。 必填项已用*标注