setInterval in a React app

前端 未结 7 534
天涯浪人
天涯浪人 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:22

    I see 4 issues with your code:

    • In your timer method you are always setting your current count to 10
    • You try to update the state in render method
    • You do not use setState method to actually change the state
    • You are not storing your intervalId in the state

    Let's try to fix that:

    componentDidMount: function() {
       var intervalId = setInterval(this.timer, 1000);
       // store intervalId in the state so it can be accessed later:
       this.setState({intervalId: intervalId});
    },
    
    componentWillUnmount: function() {
       // use intervalId from the state to clear the interval
       clearInterval(this.state.intervalId);
    },
    
    timer: function() {
       // setState method is used to update the state
       this.setState({ currentCount: this.state.currentCount -1 });
    },
    
    render: function() {
        // You do not need to decrease the value here
        return (
          
    {this.state.currentCount}
    ); }

    This would result in a timer that decreases from 10 to -N. If you want timer that decreases to 0, you can use slightly modified version:

    timer: function() {
       var newCount = this.state.currentCount - 1;
       if(newCount >= 0) { 
           this.setState({ currentCount: newCount });
       } else {
           clearInterval(this.state.intervalId);
       }
    },
    

提交回复
热议问题