如何清除反应中的settimeout

问题描述 投票:2回答:1

在每个问题组件上,我试图清除时间。所以在componentWillMount()我将启动计时器,然后在componentDidUpdate()我将清除超时。计时器似乎没有工作。计时器到期后,我会将用户推回主页。知道为什么使用clearTimeout()不工作?

class Questions extends Component { 
    constructor(props){
        super(props);
        this.state ={
            error: false,
            position: null,
            redirect: false
        } 
        this.error = this.error.bind(this);   
        this.errorFalse = this.errorFalse.bind(this); 
        this.timer = this.timer.bind(this); 
    }
    timer=()=>{
        setTimeout(() => { 
            console.log('this ran') 
            this.setState({
                redirect: true
            })

    }, 5000)
    }
    componentWillMount(){
        this.setState({
            error: false
        })
        this.timer();

    }
    componentDidUpdate(prevProps, prevState, snapshot, timer){
        console.log('updated')
        clearTimeout(this.timer);
    }
javascript reactjs settimeout cleartimeout
1个回答
6
投票

当你使用setTimeout()时它返回一个timeoutID,你用它来clear超时。

要在组件中使用它,您需要存储从timeoutID方法返回的timer

class Questions extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: false,
      position: null,
      redirect: false
    }
    this.error = this.error.bind(this);
    this.errorFalse = this.errorFalse.bind(this);
    // this.timer = this.timer.bind(this); // don't bind an arrow function
  }
  timer = () => setTimeout(() => { // return the timeoutID
    console.log('this ran')
    this.setState({
      redirect: true
    })

  }, 5000);
  componentWillMount() {
    this.setState({
      error: false
    })
    this.timeoutID = this.timer(); // cache the timeoutID
  }
  componentDidUpdate(prevProps, prevState, snapshot, timer) {
    console.log('updated')
    clearTimeout(thiis.timeoutID); // clear the timeoutID
  }
© www.soinside.com 2019 - 2024. All rights reserved.