Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - How To Delete Component When Timeout In React Js

I'm trying to figure out the React way to remove an component after timeout

i have tried with set timer like this: Removing element from DOM after set amount of time

Here is the code for my component:

import React, {Component} from 'react'

class Timer extends Component{
    constructor(props) {
        super(props);
        this.state = {
            time: 2,
            date: new Date()};
        }
    
      componentDidMount() {
        this.timerID = setInterval(
          () => this.tick(),
          1000
        );
        
      }
      tick() {
        this.setState({
          date: new Date(),
          time: this.state.time - 1 
        });
        if (this.state.time <= 0) {
            clearInterval(this.timerID);
          }
      }
      componentWillUnmount() {
          alert("Unmount")
        }
      render() {
        return (
          <div>
           Now {this.state.date.toLocaleTimeString()}. Count Down {this.state.time}
          </div>
        );
      }
    }

export default Timer
question from:https://stackoverflow.com/questions/65880254/how-to-delete-component-when-timeout-in-react-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Do you mean how to cancel an interval function if the component is already unmounted?

There is such a case that the interval call has already started right before the component is unmounted, if so you can add a flag _mounted in your class to check if the component is unmounted.

class Timer extends Component{
    _mounted = true
    timer;
    componentDidMount() {
      this.timerID = setInterval(
        () => {
          if (this._mounted) {
            this.tick()
          }
        },
          1000
      );
    }
    componentWillUnmount() {
      this._mounted = false
      window.clearInterval(this.timer)
    }
    render() {
      const { time } = this.state
      return time === 0 ? null : (
        <div>xxx</div>
      );
    }
}

export default Timer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...