react中簡單倒計時跳轉


其實在react中實現倒計時的跳轉方法有很多中,其中我認為較為好用的就是通過定時器更改state中的時間值。

首先在constructor中設置10秒的時間值:

constructor () {
    super()
    this.state={
      seconds: 10,
    };
  }

 

然后在componentDidMount中添加定時器:

componentDidMount () {
  let timer = setInterval(() => {
    this.setState((preState) =>({
      seconds: preState.seconds - 1,
    }),() => {
      if(this.state.seconds == 0){
        clearInterval(timer);
      }
    });
  }, 1000)
}

 

然后在render中添加判斷跳轉

if (this.state.seconds === 0) {
    window.location.href='http://www.cnblogs.com/a-cat/';
}

 

這種就可以完成倒計時跳轉了!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM