这是组件:
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 工作呢?
最佳答案
在 componentWillUnmount
中的类中设置一个标志。
在您的异步回调中,检查该标志是否已设置,如果已设置,则立即停止。
关于javascript - 当 Reactjs 组件中的 componentWillUnmount 时如何清除异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45063486/