简体   繁体   English

React JS 中的无限滚动,但来自 Reddit 的数据不断加载和加载

[英]Infinite Scroll in React JS, but data from Reddit keeps loading and loading

please have a look at the code and suggest what should have had done.请查看代码并建议应该做什么。

import React, {useState, useEffect} from "react";
import logo from './logo.svg';
import './App.css';
import './Table.css';
import axios from "axios";

const NEXT_PAGE = "";
function App() {
const [items, setData] = useState([]);
const [page, setPage] = useState(NEXT_PAGE);
useEffect( () => {
    axios.get(`https://www.reddit.com/r/aww.json?after=${page}`)
    .then(res=> res.data)           
    .then(data => {
        setData([...items, ...data.data.children])
        setPage(data.data.after)
    })
}, [page]);

const scrollToEnd = () => {
    setPage(page);
}

window.onscroll = function(){
    if(
        window.innerHeight + document.documentElement.scrollTop
        === document.documentElement.offsetHeight
    ){
        scrollToEnd()
    }
}


return (
    <div className="App">
        <h1>Displaying data from Reddit API</h1>
        <table>
            <thead>
            <tr>
                <th>ID</th>
                <th>Photo</th>
                <th>Content</th>
            </tr>
            </thead>
            <tbody>
                {items.length > 0 && items.map((el, i) => 
                    <tr id={el.data.id}>
                        <td>{el.data.id}</td>
                        <td><img src={`${el.data.thumbnail}`} height={`${el.data.thumbnail_height}`} width={`${el.data.thumbnail_width}`} /></td>
                        <td>{el.data.title}</td>
                    </tr>
                )}
            </tbody>
        </table>
    </div>
);      
}

export default App;

Either it keeps loading data or does not do anything once we reach at the bottom of the page.一旦我们到达页面底部,它要么继续加载数据,要么不做任何事情。 I only want the next course of data to be loaded when we reach at the bottom of the page.我只希望在我们到达页面底部时加载下一个数据过程。 I am trying to learn from various sources but as I am just starting it, I am unable to do it properly.我正在尝试从各种资源中学习,但由于我刚刚开始,我无法正确地做到这一点。 Your valuable suggestion will help me learn things in a proper way.您的宝贵建议将帮助我以正确的方式学习东西。

you are actually nevering calling the scrollToEnd() function, because you rarely get the strict equality, it will be either below or above but not strictly equal您实际上从未调用 scrollToEnd() 函数,因为您很少获得严格相等,它将低于或高于但不严格相等

give it a try with :试试看:

window.innerHeight + document.documentElement.scrollTop
        > document.documentElement.offsetHeight

also in your useEffet function you could use a cleanup function to avoid memory leaks, and also add a catch to deal with errors :同样在你的 useEffet 函数中,你可以使用清理函数来避免内存泄漏,还可以添加一个 catch 来处理错误:

useEffect( () => {
    let mounted = true

    if(mounted)
      axios.get(`https://www.reddit.com/r/aww.json?after=${page}`)
      .then(res=> res.data)           
      .then(data => {
          setData([...items, ...data.data.children])
          setPage(data.data.after)
      .catch(err => console.error (err))
      })

    return () => mounted = false;
}, [page]);

Also to avoid the infinite refetching of the data, try removing the setPage inside of your async function inside the useEffect hook此外,为了避免无限重新获取数据,请尝试在 useEffect 挂钩内删除异步函数内的 setPage


const NEXT_PAGE = 0;
function App() {
const [items, setData] = useState([]);
const [page, setPage] = useState(NEXT_PAGE);

useEffect( () => {
    let mounted = true

    if(mounted)
      axios.get(`https://www.reddit.com/r/aww.json?after=${page}`)
      .then(res=> res.data)           
      .then(data => {
          setData([...items, ...data.data.children])
      .catch(err => console.error (err))
      })

    return () => mounted = false;
}, [page]);

const scrollToEnd = () => {
    setPage(prevPage => prevPage + 1);
}

window.onscroll = function(){
    if(
        window.innerHeight + document.documentElement.scrollTop
        > document.documentElement.offsetHeight
    ){
        scrollToEnd()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 下一页数据未通过反应无限滚动加载 - next page data not loading with react infinite scroll react.js 中的无限滚动不起作用,我使用的是无限滚动组件并且它没有从下一页加载图像 - Infinite scroll in react.js not working, I am using infinite scroll component and it is not loading images from next page ReactJs 无限加载滚动分页一直在循环加载最后一页 - ReactJs Infinite loading scroll pagination keeps loading last page in loop 加载React JS组件数据时,jQuery滚动两次触发 - JQuery scroll fire twice when loading react js component data React.js从服务器加载数据 - React.js loading data from server 在 React 中加载更多数据(无限滚动)时如何避免滚动条停留在顶部 - How to avoid scrollbar staying on top when loading more data (infinite scroll) in React 反应 js c'ant 从数据库中获取 - 节点 js api 服务器不断加载 - react js c'ant fetch from database - node js api server keeps loading 对数据的无限加载做出反应,直到数据从后端出现——每个请求都有固定的数据 - React infinite loading of data till data is there from backend--fixed data is coming on every request 加载微调器永远加载 - loading spinner keeps loading forever React react-loading-skeleton持续加载 - react-loading-skeleton keeps on loading
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM