我的状态不会在setInterval函数内更新

时间:2019-07-10 15:26:31

标签: javascript reactjs setinterval setstate

我正在尝试更新setState中小时,分钟和秒的状态值,以帮助建立时钟。第一次尝试时,我尝试在setInterval内部调用一个函数,在其中使用setState更新状态。我发现代码成功输入了setTime函数,因为console.log(“ in setTime”内部)出现了。但是,状态没有更新,并且该函数在此实例之后没有运行。

我设法通过直接更新setInterval函数中的状态来解决该问题,如第二代码所示。这每秒更新一次状态,我显示的时钟显示了这些更新。但是,我不太了解为什么这种方法有效,但是第一种方法却无效。谁能向我解释一下?

//这是我的构造函数

import React from 'react';
import ReactDOM from 'react-dom';
import ButtonClick from './Components/UserInputs.js'


class Clock extends React.Component {

    constructor(props) {

        super(props);

        this.adjustForLocation = this.adjustForLocation.bind(this);
        this.tick = this.tick.bind(this)
        this.state = {CityfromChild: "", hours:0, minutes: 0, seconds: 0, 
test:''};

        this.setTime = this.setTime.bind(this)
    }

// 1次尝试。这不起作用:

tick(timeDiff){
        setInterval(this.setTime(timeDiff), 1000)

    }

    setTime(timeDiff){
        console.log("inside setTime")
        this.setState({
             seconds: new Date().getSeconds(), 
             minutes: new Date().getMinutes()
            });
        this.setState({hours: timeDiff + new Date().getHours() })
    }

// 2次尝试。这可行:

tick(timeDiff){
        this.interval = setInterval(()=> this.setState({
            hours: timeDiff + new Date().getHours(), 
            seconds: new Date().getSeconds(), 
            minutes: new Date().getMinutes() 
            })
        , 1000);
    }

0 个答案:

没有答案
相关问题