其實在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/'; }
這種就可以完成倒計時跳轉了!