我不確定它是否稱為無限滾動,但基本上,我有一個包含數千行的表格,我在 ASP.Net Core 網站上顯示。該表格具有高級布局,其中樣式強烈依賴于單元格內容。我通過控制器填充內容和行的樣式并發布一個 JSON 檔案。
由于 JS fetch api,我可以顯示 20 行表格。我可以平滑地滾動到相鄰的行
我還添加了一個單獨的滾動條,所以我可以跳到從第一行到最后一行的任何行。
問題是當我停止移動滾動條時,行仍然會更新幾秒鐘(有一些中間行,但幸運的是不是全部),直到到達目標行。似乎有一些延遲,比如我有幾個異步呼叫等待處理一個接一個地執行的更新函式。
有沒有辦法只考慮對更新函式的最新呼叫?
$('#fields-scroll').on('input change', async function () {
var row = $('#fields-scroll').val();
await scroll(row);
});
async function scroll(row) {
// Posts the metrics to the controller.
const response = await fetch(`${window.location.href}Fields/Interact/`, {
method: 'POST',
body: JSON.stringify({ Row: row}),
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
// Gets the results from the controller.
const results = await response.json();
// Makes sure that there are actual results.
if (results == null) {
return;
}
var fields = results.fields;
await populate(fields);
}
謝謝你的幫助!
uj5u.com熱心網友回復:
我認為最簡單的方法(不使用像 redux-saga 這樣的外部庫)是使用一個簡單的 debouncer 來消除滾動動作:
const handler = _.debounce(async function () {
console.log('SCROLLING');
try {
const row = $('#fields-scroll').val();
await scroll(row);
} catch (e) {
console.log(e);
}
}, 200);
$('#fields-scroll').on('input change', handler);
async function scroll(row) {
// Posts the metrics to the controller.
const response = await fetch(`${window.location.href}Fields/Interact/`, {
method: 'POST',
body: JSON.stringify({ Row: row }),
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
});
// Gets the results from the controller.
const results = await response.json();
// Makes sure that there are actual results.
if (results == null) {
return;
}
var fields = results.fields;
await populate(fields);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG ljU96qKRCWh quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" id="fields-scroll" />
如果這是您想要的效果,您可以根據自己的喜好調整去抖時間。無論如何,請記住始終將陳述句包裝在 try-catch 塊內的異步函式中,否則您將無法捕獲拋出的錯誤。
uj5u.com熱心網友回復:
難以置信,它似乎作業得很好!
我可能需要稍微調整時間以獲得一些中間更新(并了解引擎蓋下的內容:-)),但至少當我停止移動滾動條時它不會保持更新幾秒鐘。
PS 我只是將 更改const為var,因為當我重繪 頁面時它崩潰了(更準確地說,當我移回欄位頁面時)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/462302.html
標籤:javascript 异步 获取 API 无限滚动
