其实在react中实现倒计时的跳转方法有不少中,其中我认为较为好用的就是经过定时器更改state中的时间值。javascript
首先在constructor中设置10秒的时间值:java
constructor () { super() this.state={ seconds: 10, }; }
而后在componentDidMount中添加定时器:react
componentDidMount () { let timer = setInterval(() => { this.setState((preState) =>({ seconds: preState.seconds - 1, }),() => { if(this.state.seconds == 0){ clearInterval(timer); } }); }, 1000) }
而后在render中添加判断跳转this
if (this.state.seconds === 0) { window.location.href='http://www.cnblogs.com/a-cat/'; }
这种就能够完成倒计时跳转了!component