当使用 React-Query 实现无限滚动时,如何使用 React 窗口应用列表虚拟化

How to apply list virtualization using React window when infinite scroll is implemented using React-Query

提问人:Moumita Dhar 提问时间:5/24/2023 更新时间:5/24/2023 访问量:115

问:

我正在制作一个新闻应用程序,并且我已经使用 React Query 实现了无限滚动。但我的 cocern 是随着越来越多的 dom 元素被添加到 dom 中,因为无限滚动,dom 变得很重。为了解决这个问题,我想使用 React-window 实现列表虚拟化。但我做不到。 我的代码 -

async function fetchPage({ pageParam = 1 }) {
    const response = await fetch(
        `https://newsapi.org/v2/everything?q=India&pageSize=30&page=${pageParam}&apiKey=${API_KEY}`
    );

    return response.json();
}

function App() {
    const { isLoading, data, fetchNextPage, isFetchingNextPage, hasNextPage } =
        useInfiniteQuery(["news"], fetchPage, {
            getNextPageParam: (lastpage, allpages) => {
                const nextPage = allpages.length + 1;
                return lastpage.articles.length !== 0 ? nextPage : undefined;
            },
        });

    const observedElement = useRef(null);
    useEffect(() => {
        console.log("I am loading");
        if (isLoading) return;
        console.log("I am running");
        const callback = (entries) => {
            if (entries[0].isIntersecting && hasNextPage) {
                fetchNextPage();
            }
        };
        const option = { threshold: 0 };
        const observer = new IntersectionObserver(callback, option);
        const element = observedElement.current;
        observer.observe(element);
        return () => observer.unobserve(element);
    }, [hasNextPage, fetchNextPage, isLoading]);

    if (isLoading) {
        return <p>Loading ...</p>;
    }
    const news = data.pages;
    console.log(news);
    return (
        <>
            <div className="app">
                {news.map((n) =>
                    n.articles.map((a) => (
                            <article key={a.title} className="news_article">
                                <section>
                                    <img src={a.urlToImage}></img>
                                </section>
                                <h2>
                                    <a href={a.url}>{a.title}</a>
                                </h2>
                                <p>{a.description}</p>
                                <p>{a.author}</p>
                            </article>
                        
                    ))
                )}
                <div className="loader" ref={observedElement}>
                    {isFetchingNextPage && hasNextPage ? "Loading..." : "No search left"}
                </div>
            </div>
        </>
    );
}

export default App

 

数据的结构是——

{
"status": "ok",
"totalResults": 9592,
-"articles": [
-// The news articles
},

reactjs react-query virtualscroll react-infinite-scroll-component

评论


答: 暂无答案