微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ReactJS:实现无限滚动功能时页面变量未更新

如何解决ReactJS:实现无限滚动功能时页面变量未更新

我在我的应用中实现了无限滚动功能。问题是当我到达应用程序底部时,我将页面变量增加 1。但是当我在控制台上检查相同时,它总是显示 0。我无法理解这种行为。

当我将页面变量作为 onScroll 事件的 useState 钩子中的第二个参数传递时,它正在更新但滞后。

有人可以向我解释为什么会发生这种行为以及我做错了什么吗?

import { useEffect,useState } from 'react';
import './App.css';
import Card from './components/card';

function App() {
  const [cardData,setCardData] = useState([]);
  const [page,setPage] = useState(0);

  useEffect(() => {
    getCardDataAPI();
  },[]);

  // Logic for infinite Scrolling
  useEffect(() => {
    window.addEventListener('scroll',handleScroll);
    return () => window.removeEventListener('scroll',handleScroll);
  },[]);

  const handleScroll = () => {
    if (window.innerHeight + document.documentElement.scrollTop !== document.documentElement.offsetHeight)
      return;
    console.log('Fetch more list items!');
    setPage(prevstate => prevstate + 1);
    getCardDataAPI();
  };

  const getCardDataAPI = () => {
    console.log('app',page);
    fetch(`https://api.instantwebtools.net/v1/passenger?page=${page}&size=10`).
      then(async response => {
        try {
          const { data } = await response.json();
          setCardData(prevstate => [...prevstate,...data]);
        } catch (error) {
          console.log(error);
        }
      });
  };
  console.log(cardData,page);
  return (
    < div className="App" >
      <header className="App-header">
        Cards App
      </header>
      <main>
        <div>
          {cardData.map((obj,index) => <Card key={index} {...obj} />
          )}
        </div>
      </main>
    </div >
  );
}

export default App;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。