1. 程式人生 > >react實現定時器

react實現定時器

class Timer extends Component {
    state = {
        seconds: 0
    }
    tick = () => {
        const { seconds } = this.state;
        this.setState({
            seconds: seconds + 1
        })
    }
    componentDidMount() {
        this.interval = setInterval(() => this.tick(), 1000);
    }

    componentWillUnmount() {
        clearInterval(this.interval);
    }
    render() {
        return (
            <div>Seconds:{this.state.seconds}</div>
        )
    }
} 
export default Timer;