如何在Reactjs组件中的componentWillUnmount时清除一个异步函数?

Cin*_*que 6 javascript asynchronous reactjs cleartimeout

这是组件:

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工作?

SLa*_*aks 5

在你的班级里面设置一个标志componentWillUnmount.

在异步回调中,检查是否已设置该标志,如果是,则立即停止.


Ani*_*ift 5

您当然可以按照@SLaks 的建议设置一个标志。这类似于 isMounted 模式。** 注意我更改为 componentdidmount 这是我认为更好的模式 **

class ChartComp extends Component{
    constructor(props){
        super(props);
        this.timer = null;
        this.loadData = this.loadData.bind(this);
    }

    componentDidMount() {
      this._mounted = true;
      this.loadData();
    }

    componentWillUnmount(){
        this._mounted = false;
        if(this.timer){
            clearTimeout(this.timer);
        }
    }

    loadData(){
        //...
        getJSON(url, msg=>{ //get data from server
            if(msg.success && this._mounted){
                //...
                this.timer = setTimeout(()=>{this.loadData()}, 30000); //get data and rerender the component every 30s
            }
        })
    }

    render(){
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读更多关于为什么该模式被弃用的信息 。但是,这样做最终会在 getJSON 以及随后的超时上都需要标志,因为基本上你需要将可取消的承诺链接在一起(你想停止任何步骤)道路)

需要考虑的另一种范例是为此使用可观察链。请参阅此博客了解详细信息