見代碼
class View extends Component { constructor(props){ super(props); this.state = { cancel:null, cancel2:null } } //簡易版 async getApi2(url,cfg,headers){ let data = await axios.get(url,{params:cfg}, { headers: headers }) return data; } // 增加取消版 async getApi2(url,cfg,headers,fn){ const CancelToken = await axios.CancelToken; let data = await axios.get(url,{ params:cfg, cancelToken: new CancelToken(function executor(c) { //取消請求官方提供了方法就是在new一個CancelToken函數的參數,我們主要實現的就是想讓 這個參數(函數)c 被外部使用 //所以使用了 第四個參數 函數 使用參數進行返回 fn(c) }) }, { headers: headers }) return data; } componentDidMount(){ //如下代碼在調用時增加了第四個參數 ,在四個參數中進行重新賦值使用 this.getApi2('/home/mediareports',{ 'page_number':1, 'page_size':5 },{},(c)=>{ 把參數(函數)c給到state cancel this.state.cancel = c }).then((res)=>{ console.log(res.data.data) }) //以下就可以使用取消終止請求了 // setTimeout( ()=>{ // this.state.cancel() // }, 100) this.getApi3('/home/mediareports',{ 'page_number':1, 'page_size':5 },{},(c)=>{ this.state.cancel2 = c }).then((res)=>{ console.log(res.data.data) }) setTimeout( ()=>{ this.state.cancel2.cancel('請求已取消') }, 100) } async getApi3(url,cfg,headers,fn){ const CancelToken = await axios.CancelToken; const source = await CancelToken.source(); await