码迷,mamicode.com
首页 > 其他好文 > 详细

react中简单倒计时跳转

时间:2018-09-08 15:31:26      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:更改   rest   win   class   second   time   timer   ref   seconds   

其实在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/‘;
}

 

这种就可以完成倒计时跳转了!

 

react中简单倒计时跳转

标签:更改   rest   win   class   second   time   timer   ref   seconds   

原文地址:https://www.cnblogs.com/a-cat/p/9607980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!