javascript - 即使在 React 中到达底部,页面也不会向下滚动?
问题描述
在一个 React 项目中,我将某些项目映射为初始大小为 5,当到达底部时,预计会加载更多 5 个项目,并随着页面超过 40 个而相应增加。它就像无限滚动。但是,这里滚动停止,只有 15 个元素和第 3 页。以下是参考代码
const [state, setState] = useState([]);
const [page, setPage] = useState(PAGE_NUMBER);
const scrollToEnd = () => {
setPage(page + 1);
};
console.log("Page", page);
useEffect(() => {
fetch(`https://api.instantwebtools.net/v1/passenger?page=${page}&size=5`)
.then((res) => res.json())
.then((json) => setState([...state, ...json.data]));
}, [page]);
window.onscroll = function () {
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
scrollToEnd();
}
};
return (
<>
{state.length > 0 &&
state.map((el, i) => (
<div key={i} className="container">
<h4>{el.id}</h4>
<h4>{el.name}</h4>
</div>
))}
</>
);
任何适当的解决方案都受到高度赞赏
以下是代码框链接:https ://codesandbox.io/s/material-demo-forked-sn31v
解决方案
您可以添加一个 useEffect 并在该 useEffect 中添加一个事件侦听器以进行滚动并检查用户滚动是否足够。
工作克隆项目:https ://codesandbox.io/s/material-demo-forked-rr9th
useEffect(() => {
const eventListener = document.addEventListener("scroll", () => {
const windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;
// user scrolled enough
if (windowRelativeBottom <= document.documentElement.clientHeight + 100) {
setPage(pageCount => pageCount + 1);
}
})
}, [])
资源
推荐阅读
- node.js - async的“queue”方法的第二个参数的作用是什么?
- azure-container-registry - 在不可预测的时间推送到 Azure 容器注册表非常缓慢
- r - 根据其他值查找值
- c# - 如何使用 while 循环替换在字符串中出现多次的子字符串?
- regex - 找出数组公式语法
- .net - 没有枚举的文件操作
- sql-server - 我可以根据外部表对 SQL 中的排序列进行优先级排序吗
- sql - Vertica ILIKE 大型数据集
- javascript - 平日。如何在以下代码中修复此错误?
- matlab - 当我应用 notboxplot 函数生成 beeswarm 箱线图时,如何更改标记透明度?