【问题标题】:Is this good practice for updating the state of a React component from a function within another function?这是从另一个函数中的函数更新 React 组件状态的好习惯吗?
【发布时间】:2019-02-22 16:53:20
【问题描述】:

首先,我的代码有效,问题更多是关于良好实践,而且我是 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 函数中,但我觉得可能有更清洁的方法,有吗?

谢谢

【问题讨论】:

  • function(){改成() =&gt; {然后你就可以this.setState
  • @Jonas Wilms 谢谢,正如我在下面评论的那样,我真的应该更好地理解箭头函数......

标签: javascript reactjs this


【解决方案1】:
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)
}

【讨论】:

  • 谢谢,这就是我想要的。我最好更好地研究箭头函数,因为我总是忘记它。
猜你喜欢
  • 2021-03-15
  • 2020-01-01
  • 2011-07-17
  • 2023-04-05
  • 2013-09-30
  • 2022-08-05
  • 1970-01-01
  • 2017-10-11
  • 2015-02-18
相关资源
最近更新 更多