谢谢你的问题。关于使用 nextHandler 的文档确实可以使用改进。无论如何,我将尝试解释它是如何工作的。
通常 IAS 使用选择器来查找下一页的 url。然后它加载页面并提取元素并将它们附加到 DOM。如果你使用 nextHandler,你将完全绕过这个行为。这意味着您必须自己获取数据(在本例中为 JSON)并在 DOM 中插入新元素。
这是一个带有注释的示例来解释它的作用。
首先,假设我们的 movie(1..n).json 具有以下格式:
[
{
Title: 'item1',
Plot: 'description1'
}, {
Title: 'item2',
Plot: 'description2'
}
]
现在实现nextHandler:
import InfiniteAjaxScroll from "@webcreate/infinite-ajax-scroll";
function nextHandler(pageIndex) {
// we use the fetch api to load the next page. Any http client library will do, like axios.
return fetch("./static/movies"+pageIndex+".json")
// use the response as json
.then((response) => response.json())
// process the actual json data
.then((jsonData) => {
// create an array to store our html elements in memory
let elements = [];
// we loop over the items in our json and create an html element for each item
jsonData.forEach(function (item) {
const template = `<div class="item">
<h1>${item.Title}</h1>
<p>${item.Plot}</p>
</div>`;
const element = document.createElement("div");
element.innerHTML = template.trim();
elements.push(element.firstChild);
});
// now use IAS's append method to insert the elements
// it's import that we return the append result, as it's an promise
return this.append(elements);
})
// page 3 returns a 404, returning false here indicates there are no more pages to load
.catch(() => false);
}
window.ias = new InfiniteAjaxScroll(".container", {
item: ".item",
next: nextHandler,
pagination: false
});
我还准备了一个关于 Codesandbox 的交互式演示:
https ://codesandbox.io/s/serene-einstein-f73em