【发布时间】:2019-03-25 14:19:14
【问题描述】:
我想获取数据,如果获取时出错。我想等待 1000 秒,然后再次获取数据。
问题是在方法 settingTimeout() this.setState({timerStatus: true});我期待重新渲染整个应用程序并在 console.log 中渲染超时。但由于某种原因,它没有这样做。我尝试在 settingTimeout() 中使用 this.forceUpdate();没有太多的运气。 React similiar example
this.state = {
retryTimer: 1000,
timerStatus: false,
}
}
componentDidMount(){
if(this.state.timerStatus){
console.log('timeout');
}
this.newGame();
}
newGame =() => {
Axios.get(
this.state.apiBase + 'nexGame',
this.state.headers
)
.then(response =>{
console.log(response)
}
})
.catch(error =>{
this.settingTimeout();
})
}
settingTimeout = () =>{
this.setState({timerStatus: true});
if(this.state.retryTimer === 0){
this.newGame();
}
}
【问题讨论】:
-
this可能不是您所期望的。将newGame和settingTimeout制作成箭头函数,看看是否可行。newGame = () => { ... }; settingTimeout = () => { ... }; -
retryTimer 在哪里倒计时?你设置了超时但没有指定时间间隔?
-
我没有包括设置间隔,因为首先我需要解决打印 console.log(timeout);
-
我认为它没有被记录的原因是因为 setState 还没有完成,因为它是一个异步操作,在 componentDidUpdate 中你应该能够看到结果
-
是的,你说得对。将 if 语句放入 componentDidUpdate 打印超时
标签: javascript reactjs axios