react中簡單倒計時跳轉

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

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

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

2.然後在componentDidMount中添加定時器:

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

3.然後在render中添加判斷跳轉:

if (this.state.seconds === 0) {
    window.location.href='www.baidu.com';
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章