Q1:在報表導出中,使用了fetch,現(xiàn)在需要處理一個情況:接口會有返回404的狀態(tài)。
handleExport = () =>{
if( this.state.type === ''){
message.warning('請先選擇區(qū)域');
}else{
getToken().then(token=>{
const url = `${Url()}shopping_mall/reports/rank/export?from_date=${getStartDate(this.state.stDate)}&to_date=${getEndDate(this.state.endDate)}&order_by=${this.state.orderBy}&${this.state.type}`;
const fetchOption = {
method: 'GET',
headers: {
'X-Requested-With': '1000',
Authorization: `Bearer ${token}`,
},
};
// 開始所需數(shù)據(jù)的下載
fetch(url, fetchOption)
.then(response => response.blob())
.then(blob=>{
const aUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = aUrl;
document.body.appendChild(a);
a.download= "排行數(shù)據(jù)詳細表.csv";
a.click();
setTimeout(()=>{
document.body.removeChild(a);
window.URL.revokeObjectURL(aUrl);
},2000);
})
})
}
}
修改后
handleExport = () =>{
if( this.state.type === ''){
message.warning('請先選擇區(qū)域');
}else{
getToken().then(token=>{
const url = `${Url()}shopping_mall/reports/rank/export?from_date=${getStartDate(this.state.stDate)}&to_date=${getEndDate(this.state.endDate)}&order_by=${this.state.orderBy}&${this.state.type}`;
const fetchOption = {
method: 'GET',
headers: {
'X-Requested-With': '1000',
Authorization: `Bearer ${token}`,
},
};
return new Promise((resolve, reject) => {
// 開始所需數(shù)據(jù)的下載
fetch(url, fetchOption)
.then(response => {
// console.log('response = ', response);
if(response.ok){
return response.blob();
}else{
message.warning('暫無數(shù)據(jù)導出');
throw `${response.statusText}`;
// throw new Error("error");
// message.error('')
}
})
.then(blob=>{
const aUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = aUrl;
document.body.appendChild(a);
a.download= "排行數(shù)據(jù)詳細表.csv";
a.click();
setTimeout(()=>{
document.body.removeChild(a);
window.URL.revokeObjectURL(aUrl);
},2000);
})
.catch(err => {
reject(err);
});
});
})
}
}
其中有個eslint提示語法報錯:
expected an object to be thrown. (no-throw-literal)
因為語法要求寫成這種:throw new Error(${response.statusText});,(語法規(guī)范:https://cn.eslint.org/docs/rules/no-throw-literal),于是這樣改了,但是頁面導出時,一旦是404的狀態(tài),就會跳轉到報錯頁面,用戶體驗不友好,目前不知如何解決。先Mark
于是還是寫成語法報錯形式:throw${response.statusText};,這樣不會跳轉到報錯界面。