React組件銷燬中清理異步操作和取消請求

情況一: 阻止異步操作

componentWillUnmount() {
  this.setState = (state, callback) => {
    return
  }
}

情況二: 阻止請求(axios)

window.CancelToken = Axios.CancelToken;  //放在封裝的js中


constructor(props) {
	this.state=store.getState()
	this.source = window.CancelToken.source() //生成取消令牌用於組件卸載阻止axios請求
}

componentDidMount = () => {
	window.Axios({
            cancelToken:this.source.token,
            url: window.ApiName.ApiGetBreakdownReason,
            method: 'post',
            data: {}
        }).then((res)=> {
          
        }).catch(err => {
            console.log(err)
        });
}
componentWillUnMount = () => {
    //阻止請求
    this.source.cancel('組件卸載,取消請求');
}

情況三: 清除定時

var timer;

componentDidMount = () => {
     timer = setTimeout(() => {
        this.setState({data:123456789})
    },5000)
}
componentWillUnMount = () => {
    if(timer){
        clearTimeout(timer)
    } 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章