这是从另一个函数中的函数更新React组件状态的良好实践吗?

问题描述 投票:0回答:1

首先,我的代码工作,问题更多是关于良好实践,我是React的新手。

我想做的是一个简单的倒计时,我有问题使用

this.setState(...)

这没有定义。

代码现在是:

componentDidMount(){
    this.updateCountdown();
}

updateCountdown(){

    var countDownDate = new Date("Dec 14, 2019 12:00:00").getTime();

    var parent = this;        

    var x = setInterval(function(){
        var distance = countDownDate - new Date().getTime();

        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        parent.setState(state => ({
            countdown : {
                seconds : seconds,
                minutes : minutes,
                hours : hours,
                days : days
            }
        }));

        if(distance < 0){
            clearInterval(x);
        }

    }, 1000)
}

正如你所看到的那样

var parent = this;

这样我就可以用了

parent.setState(...)

在setInterval函数中,但我觉得可能有一个更干净的方式,是吗?

谢谢

javascript reactjs this
1个回答
0
投票
componentDidMount(){
    this.updateCountdown();
}

updateCountdown(){
    var countDownDate = new Date("Dec 14, 2019 12:00:00").getTime();
    var x = setInterval(() =>{
        var distance = countDownDate - new Date().getTime();

        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

       this.setState(state => ({
            countdown : {
                seconds : seconds,
                minutes : minutes,
                hours : hours,
                days : days
            }
        }));

        if(distance < 0){
            clearInterval(x);
        }

    }, 1000)
}
© www.soinside.com 2019 - 2024. All rights reserved.