这是组件:
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 工作呢?