setInterval in a React app

前端 未结 7 539
天涯浪人
天涯浪人 2020-11-30 20:46

I\'m still fairly new at React, but I\'ve been grinding along slowly and I\'ve encountered something I\'m stuck on.

I am trying to build a \"timer\" component in Re

7条回答
  •  一个人的身影
    2020-11-30 21:19

    Updated 10-second countdown using class Clock extends Component

    import React, { Component } from 'react';
    
    class Clock extends Component {
      constructor(props){
        super(props);
        this.state = {currentCount: 10}
      }
      timer() {
        this.setState({
          currentCount: this.state.currentCount - 1
        })
        if(this.state.currentCount < 1) { 
          clearInterval(this.intervalId);
        }
      }
      componentDidMount() {
        this.intervalId = setInterval(this.timer.bind(this), 1000);
      }
      componentWillUnmount(){
        clearInterval(this.intervalId);
      }
      render() {
        return(
          
    {this.state.currentCount}
    ); } } module.exports = Clock;

提交回复
热议问题