小编Cin*_*que的帖子

如何在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(){
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

在卸载组件之前将调用clearTimeout函数.但是计时器处于异步功能,它在我收到服务器响应后再次启动.那么我怎样才能使clearTimeout工作?

javascript asynchronous reactjs cleartimeout

6
推荐指数
2
解决办法
5571
查看次数

标签 统计

asynchronous ×1

cleartimeout ×1

javascript ×1

reactjs ×1