情況一: 阻止異步操作
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)
}
}