我的计时器无法启动,我不知道为什么?

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

我正在创建一个计时器功能。现在,我只想在组件加载时启动计时器,因此我将操作放在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;
    }
reactjs timer
2个回答
1
投票

setState是异步的,所以当你将timerStarted设置为true然后立即检查它时,你不能保证有最新鲜的状态。一个好的解决方案是使用setState的第二个参数,这是一个在实际更新状态后触发的回调。

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

0
投票

这是我使用的Component的一个例子。

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});
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.