gpt4 book ai didi

javascript - 当 Reactjs 组件中的 componentWillUnmount 时如何清除异步函数?

转载 作者:数据小太阳 更新时间:2023-10-29 05:11:38 25 4
gpt4 key购买 nike

这是组件:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com