我的计时器无法启动,我不确定为什么吗?

时间:2019-03-29 19:42:18

标签: reactjs timer

我正在创建计时器功能。现在,我只希望计时器在组件加载时启动,所以我将动作放在componentWillMount中。由于某些原因,计时器没有启动,我不知道为什么。

constructor(props) {
        super(props);
        this.state = {
            timerStarted: false,
            timerStopped: true,
            hours: 0,
            minutes: 0,
            seconds: 0,
            captures: []
        }
        //We store the Timer Started and Stoped bool also the cptures array for rendering it on the app.

        this.handleTimerStart = this.handleTimerStart.bind(this);
    }

    handleTimerStart(e) {
        e.preventDefault();
        alert('Timer Started!');
        if(this.state.timerStopped) {
            this.timer = setInterval(() => {
                this.setState({timerStarted: true, timerStopped: false});
                if(this.state.timerStarted) {
                    if(this.state.seconds >= 60) {
                        this.setState((prevState) => ({ minutes: prevState.minutes + 1, seconds: 0}));
                    }
                    if(this.state.minutes >= 60) {
                        this.setState((prevState) => ({ hours: prevState.hours + 1, minutes: 0, seconds: 0}));
                    }
                    this.setState((prevState) => ({ seconds: prevState.seconds + 1 }));
                }

            }, 1000);
        }
    }

    handleTimerStop() {
        this.setState({timerStarted: false, timerStopped: true});
        clearInterval(this.timer);
        /*this.handleTimerStop.bind(this); <--this is the stop action method*/
    }

    componentDidMount() {
        this.handleTimerStart;
    }

2 个答案:

答案 0 :(得分:1)

setState是异步的,因此当您将timerStarted设置为true并立即对其进行检查时,就不能保证它具有最新状态。一个好的解决方案是使用setState的第二个参数,这是在状态实际更新后触发的回调。

this.setState({timerStarted: true, timerStopped: false}, () => {
    if(this.state.timerStarted) {
    // do all of your things
    }
});

答案 1 :(得分:0)

这是我使用的组件示例。

class Timer extends Component{
    constructor(...props) {
        super(...props)

        this.state = {
            seconds: 0,
            minutes: 0,
            hours: 0,
            timerStopped: true,
            inter: setInterval(this.timer, 1000)
        }
    }

    timer = event => {
        const {hours, minutes, seconds, timerStopped} = this.state;
        if(!timerStopped){
            seconds += 1;
            if(seconds >= 60){
                minutes += 1;
                seconds = 0;
            }
            if(minutes >= 60){
                hours += 1;
                minutes = 0;
            }
            this.setState({hours, minutes, seconds});
        }
    }
}