ajax 有終止請求 abort 那 axios 有沒有,怎么實現


見代碼

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 fn(source) let data = await axios.get(url,{ params:cfg, cancelToken: source.token }, { headers: headers }) return data; } componentWillUnmount(){ //取消/home/mediareports這個接口的請求 this.state.cancel() this.state.cancel2.cancel('請求已取消') } render(){ return( <div>111</div> ) } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM