以下是部分:前组件被卸载如何清除在Reactjs组件中componentWillUnmount时超时的异步函数?
class ChartComp extends Component{
constructor(props){
super(props);
this.timer = null;
this.loadData = this.loadData.bind(this);
}
componentWillMount(){
this.loadData();
}
componentWillUnmount(){
if(this.timer){
clearTimeout(this.timer);
}
}
loadData(){
//...
getJSON(url, msg=>{ //get data from server
if(msg.success){
//...
this.timer = setTimeout(()=>{this.loadData()}, 30000); //get data and rerender the component every 30s
}
})
}
render(){
//...
}
}
的clearTimeout函数将被调用。但是定时器处于异步函数中,并且在从服务器获得响应后再次启动。那么我该如何让clearTimeout工作?