优化React和React Query的数据查询,仅在组件在视口中时进行
P粉714890053
P粉714890053 2023-08-28 17:26:18
[React讨论组]
<p>我有一个使用React渲染帖子组件列表的页面,对于每个帖子组件,我都会获取与该帖子相关的评论,并使用React Query库将其显示在内部。问题是,当用户加载帖子页面时,React Query会一次性加载所有帖子的所有评论,这会导致我的后端变慢。</p> <p>我想实现一个机制,只有当用户滚动到特定的帖子时才加载评论,而不是在页面渲染时一次性加载所有内容。如何使用React和React Query实现这一点?</p> <p>这是我当前的示例代码来获取和显示评论:</p> <p>我的帖子组件</p> <p> <pre class="brush:js;toolbar:false;">import React from 'react'; import { useQuery } from 'react-query'; const PostComponent = ({ post }) =&gt; { const { data, isLoading, error } = useQuery( ['comments', post.id], () =&gt; fetchComments(post.id) ); return ( &lt;div&gt; {/* 渲染你的帖子组件 */} {isLoading &amp;&amp; &lt;div&gt;正在加载评论...&lt;/div&gt;} {error &amp;&amp; &lt;div&gt;获取评论时出错&lt;/div&gt;} {data &amp;&amp; ( &lt;div&gt;&lt;p&gt;{post.title}&lt;/p&gt; &lt;/div&gt; )} &lt;/div&gt; ); };</pre> </p> <p>我的帖子页面组件 <pre class="brush:js;toolbar:false;">import React from 'react'; import { useQuery } from 'react-query'; const PostsPage = () =&gt; { const { data, isLoading, error } = useQuery('posts', fetchPosts); return ( &lt;div&gt; {isLoading &amp;&amp; &lt;div&gt;正在加载帖子...&lt;/div&gt;} {error &amp;&amp; &lt;div&gt;获取帖子时出错&lt;/div&gt;} {data &amp;&amp; data.map((post) =&gt; ( &lt;PostComponent key={post.id} post={post} /&gt; ))} &lt;/div&gt; ); };</pre> </p>
P粉714890053
P粉714890053

全部回复(1)
P粉323224129

为了实现这个目标,您需要两个组件。

  1. Intersection Observer API - 用于确定组件是否在视口中
  2. React Query Dependent Queries(enabled标志)- 在组件在视口中时启用查询的使用
为了简化在React应用中与Intersection Observer API的交互,您应该使用来自react-intersection-observer库的useInView钩子。
import React from 'react';
import { useQuery } from "react-query";
import { useInView } from "react-intersection-observer";

const PostComponent = ({ post }) => {
  const { ref, inView } = useInView();

  const { data, isLoading, error } = useQuery(
    ["comments", post.id],
    () => fetchComments(post.id),
    // the useQuery hook will fetch only when inView is enabled
    { enabled: inView }
  );

  return (
    <div ref={ref}>
      {isLoading && <div>Loading comments...</div>}
      {error && <div>Error fetching comments</div>}
      {data && (
        <div>
          <p>{post.title}</p>{" "}
        </div>
      )}
    </div>
  );
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号