Javascript 在react js中的prop更改之前,使用setTimeout重新呈现组件的正确方法是什么
我有一个日历组件,它异步获取componentDidMount上的日历事件。API可能会返回一个响应,表示日历当前不可用,因此在这种情况下,我希望组件每5秒重新获取一次数据,直到成功 我试过类似的东西Javascript 在react js中的prop更改之前,使用setTimeout重新呈现组件的正确方法是什么,javascript,reactjs,Javascript,Reactjs,我有一个日历组件,它异步获取componentDidMount上的日历事件。API可能会返回一个响应,表示日历当前不可用,因此在这种情况下,我希望组件每5秒重新获取一次数据,直到成功 我试过类似的东西 componentWillReceiveProps(nextProps){ if(nextProps.data.calendarBuildStatusCode){ this.setState({isBuildingCalendar: true}); setTimeout(()
componentWillReceiveProps(nextProps){
if(nextProps.data.calendarBuildStatusCode){
this.setState({isBuildingCalendar: true});
setTimeout(()=>{
this.fetchEvents();
}, 5000)
}else{
this.setState({isBuildingCalendar: false});
}
}
其中nextrops.data.calendarBuildStatusCode
表示我从API中得到日历仍然不可用的指示。和this.setState({isBuildingCalendar:true})
只负责显示微调器,直到日历可用
this.fetchEvents()
是对API的调用,用于获取日历事件,它将导致重新渲染
上面的代码不起作用(我知道它不起作用),我只是想让大家知道我想实现什么,但不知道如何实现
任何关于如何使用setTimout重新渲染直到更改道具的建议都非常好。您需要做的就是利用
clearTimeout
并在fetchEvents
api调用中使用它
componentWillReceiveProps(nextProps){
if(nextProps.data.calendarBuildStatusCode){ // Probably you should also add a conditional check here that signifies a change in data, otherwise everytime `calendarBuildStatusCode` is `true` and `componentWillReceiveProps` is called this function will execute.
this.timerID = setTimeout(()=>{
this.fetchEvents();
}, 5000)
}
}
现在在fetchEvents函数中
fetchEvents(){
ApiCall().then(() => {
clearTimeout(this.timerID);
});
}
为什么要投否决票?除了每隔5秒就攻击一次糟糕的服务器,当它已经很紧张的时候:)到处都是仇恨者谢谢,clearTiemout做了这个把戏。。。仍然不确定为什么会被否决,我知道每5秒点击一次服务器不是最佳方式,但这就是我得到的任务要求我做的。。。