在我的項目中,我正在遷移到React,因此不加載JQuery。由於我沒有JQuery了,對於AJAX調用,我正在使用fetch。使用JQuery,我可以鉤住AJAX調用的開始和結束,因此將光標更改爲微調器非常容易。在抓取中我找不到類似的鉤子。有沒有辦法做到這一點,而不是在每個單獨的AJAX調用中改變它?使用提取API時在AJAX調用期間顯示微調器
很多谷歌搜索只是不斷找到答案... JQuery。
在我的項目中,我正在遷移到React,因此不加載JQuery。由於我沒有JQuery了,對於AJAX調用,我正在使用fetch。使用JQuery,我可以鉤住AJAX調用的開始和結束,因此將光標更改爲微調器非常容易。在抓取中我找不到類似的鉤子。有沒有辦法做到這一點,而不是在每個單獨的AJAX調用中改變它?使用提取API時在AJAX調用期間顯示微調器
很多谷歌搜索只是不斷找到答案... JQuery。
你去那裏,我覺得代碼是非常不言自明:
// Store a copy of the fetch function
var _oldFetch = fetch;
// Create our new version of the fetch function
window.fetch = function(){
// Create hooks
var fetchStart = new Event('fetchStart', { 'view': document, 'bubbles': true, 'cancelable': false });
var fetchEnd = new Event('fetchEnd', { 'view': document, 'bubbles': true, 'cancelable': false });
// Pass the supplied arguments to the real fetch function
var fetchCall = _oldFetch.apply(this, arguments);
// Trigger the fetchStart event
document.dispatchEvent(fetchStart);
fetchCall.then(function(){
// Trigger the fetchEnd event
document.dispatchEvent(fetchEnd);
}).catch(function(){
// Trigger the fetchEnd event
document.dispatchEvent(fetchEnd);
});
return fetchCall;
};
document.addEventListener('fetchStart', function() {
console.log("Show spinner");
});
document.addEventListener('fetchEnd', function() {
console.log("Hide spinner");
});
這裏是一個活生生的例子: https://jsfiddle.net/4fxfcp7g/4/
取得可靠性,您可以在then()中添加微調停止函數,這是在收到響應後調用的。並將其包裝在另一個頭文件和鉤子函數中。
function ajax(someUrl, method) {
var myHeaders = new Headers();
var myInit = {
method: method,
headers: myHeaders
};
showSpinner();
return fetch(someUrl, myInit).then(function(response) {
//... do some with response
hideSpinner();
return response;
}).catch(function(error) {
//... tell the user the request failed and hide the spinner
hideSpinner();
return error;
});
}
ajax('example.com').then(function(response) {
// ...
}).catch(function(error) {
// show error
});
是的,謝謝,我知道,但這涉及到將showSpinner()和hideSpinner()與每個AJAX調用... –
我想你誤解了這個問題,OP想掛鉤每個抓取調用的開始和結束。 –
@JimArcher確實......也許包裝它在一些功能?並調用該包裝而不是獲取?我改變了例子。 – rie
當fetch
開始發生,你可以做什麼,你setState
裝載作爲true
。然後,一旦抓取完成,您可以加載setState
作爲加載是false
。並根據當前狀態顯示微調器。
例如,
class SomeComponent extends React.Component {
constructor(props) {
super(props);
this.state = { loading: false };
}
loadData(e) {
e.preventDefault();
this.setState({ loading: true });
fetch(....).then(res => res.json()).then(resJson => {
// do other stuff here.
this.setState({ loading: false });
});
}
render() {
return (
<div>
<DisplayComponent />
<button onClick={this.loadData}>Click Me</button>
{ this.state.loading ? <Spinner /> : null }
</div>
);
}
}
全局鉤子在jQuery中是一個糟糕的主意,這並沒有停止。爲你的應用程序正在做的每個請求做微調。 – Bergi
@Bergi爲什麼全球掛鉤是一個壞主意? –
因爲您可能正在使用自己的「提取」請求的庫,並且您不想攔截它們。或者您可能希望從攔截*所有*您自己的請求中遷移出去。爲了增加可維護性,只需編寫自己的封裝函數,它可以處理微調器,然後在需要使用微調器進行請求時調用它。 – Bergi