首页 > 解决方案 > 即使在 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

标签: javascriptreactjs

解决方案


您可以添加一个 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);
      }
    })
  }, [])

资源


推荐阅读