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';
}