简体   繁体   中英

How to use setInterval method in react for handling event in react?

I am working on the Pomodoro Clock Project and I am wondering how I can make the setInterval method to work in react.

I have a code something like this :

class Pomodoro extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 25,
        };

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

    handleStartStop() {
        let counter = setInterval(timer, 1000);
        this.state.count *= 60;
        function timer() {
            this.setState({
                count: (this.state.count -= 1),
            });
        }
    }

    render() {
        return (
            <div>
                <div>
                    <p id="timer-label"> Session</p>
                    <p id="time-left">{this.state.count}</p>
                </div>

                <button id="start_stop" onClick={this.handleStartStop}>
                    Start/Stop
                </button>
            </div>
        );
    }
}

What I want to happen is , when I click the Start/Stop button . the {this.state.count} will decrement by 1 but I don't know how to use setInterval while handling events.

Every comment and suggestions is appreciated.

You can use an arrow function in order to have the correct this in your timer callback:

handleStartStop() {
    if (this.timer) {
        this.timer = clearInterval(this.timer);
        return null;
    }

    this.timer = setInterval(() => this.setState(prevState => 
        if (prevState.count === 0) {
            this.timer = clearInterval(this.timer);
            return null;
        }

        return {
            count: prevState.count - 1,
        };
    ), 1000);
}

Also note that when updating based on state you should always use the version of setState() that accepts a function where the first parameter is the previous state. This is because setState() is async and react may batch multiple calls to it. So you can't rely on the current state in the moment of calling setState() .

Also don't forget to clear the timer when the comonent unmounts:

componentWillUnmount() {
   clearInterval(this.timer);
}

Otherwise your callback will try to update the state after the component did already unmount which will lead to ugly warnings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM