首页 > web前端 > js教程 > 正文

在实践中反应:处理HTTP请求

心靈之曲
发布: 2025-02-08 09:18:18
转载
910人浏览过

处理http请求

这是一种常见的方法,您可能已经看到了许多代码的示例,这些代码在组件中进行了http调用,更改的细节,例如使用或axios的使用或状态的管理方式

>您可能已经看到了如何将此代码重新放置为自定义钩子,但让我们再次进行

此组件相对简单,您在组件中具有3个状态,以表示的状态 申请

>使用useefect仅在安装组件时执行一次,并且是制造

整个请求有效
第一种方法:

import { useeffect, usestate } from "react";

function app() {
  const [isloading, setisloading] = usestate(false);
  const [error, seterror] = usestate<any>(null);
  const [data, setdata] = usestate<any>(null);

  useeffect(() => {
    const fetchdata = async () => {
      setisloading(true);

      const response = await fetch("https://fakestoreapi.com/products");

      if (!response.ok) throw new error("failed to fetch data");

      const data = await response.json();

      setdata(data);
      setisloading(false);
    };

    fetchdata().catch((e) => seterror(e));
  }, []);

  return (
    <div>
      {isloading && <p>loading...</p>}

      {error && <p>{error.message}</p>}

      {data && <pre class="brush:php;toolbar:false">{json.stringify(data)}
登录后复制
} ); } export default app;
在钩子中分开获取逻辑

第二种方法

在这种方法中,我们在自定义挂钩中分离出fetch逻辑,在任何组件中都可以重复使用,

但是我们也降低了组件的责任,现在只需要处理国家的渲染和> 申请

>但这仍然可以改善,应用程序组件仍然需要处理提出请求的逻辑,尽管不是

> 需要处理请求的状态

第二种方法:


// usefetch.tsx
import { useeffect, usestate } from "react";

type usefetchparams<t> = {
  fetcher: () => promise<t>;
  querykey: string[];
};

export function usefetch<t>({ fetcher, querykey }: usefetchparams<t>) {
  const [isloading, setisloading] = usestate(false);
  const [error, seterror] = usestate<any>(null);
  const [data, setdata] = usestate<t | null>(null);

  const querykeystring = json.stringify(querykey);

  useeffect(() => {
    const fetchdata = async () => {
      setisloading(true);

      const data = await fetcher();
      setdata(data);

      setisloading(false);
    };

    fetchdata().catch((e) => seterror(e));
  }, [querykeystring]);

  return { isloading, error, data };
}
登录后复制
// app.tsx
import { usefetch } from "./usefetch.tsx";

const endpoint = "https://fakestoreapi.com/products";

function app() {
  const { isloading, error, data } = usefetch({
    querykey: [endpoint],
    fetcher: async () => {
      const response = await fetch(endpoint);
      if (!response.ok) throw new error("failed to fetch data");
      return response.json();
    },
  })

  return (
    <div>
      {isloading && <p>loading...</p>}

      {error && <p>{error.message}</p>}

      {data && <pre class="brush:php;toolbar:false">{json.stringify(data)}
登录后复制
} ); } export default app;
在自定义挂钩中分开请求

>现在,这就是我认为理想的责任分离。

>自定义挂钩使用fect,负责处理提出请求的逻辑;

hook productuctfindall负责制作产品申请;

应用程序组件负责处理产品渲染和请求状态

第三种方法

    // useproductfindall.tsx
    import { usefetch } from "./usefetch.tsx";
    
    
    const endpoint = "https://fakestoreapi.com/products";
    
    
    async function fetchproductfindall(params = {}) {
      const searchparams = new urlsearchparams(params);
    
      const response = await fetch(endpoint + `?${searchparams.tostring()}`);
      if (!response.ok) throw new error("failed to fetch data");
      return response.json();
    }
    
    export function useproductfindall(params = {}) {
      return usefetch({
        querykey: [endpoint, params],
        fetcher: () => fetchproductfindall(params)
      });
    }
    
    登录后复制
    // App.tsx
    import { useProductFindAll } from "./useProductFindAll.tsx";
    
    function App() {
      const { isLoading, error, data } = useProductFindAll({ limit: 6 })
    
      return (
        <div>
          {isLoading && <p>Loading...</p>}
    
          {error && <p>{error.message}</p>}
    
          {data && <pre class="brush:php;toolbar:false">{JSON.stringify(data)}
    登录后复制
    } ); } export default App;
  • 如果您有经验或知道react-query库,则可以看到hook usefetch非常
  • 类似的
  • 使用react-query的钩子,这是真的 react-want是一个库,可以提取提出申请的逻辑,并且是处理
  • >的绝佳替代方法 后端的后端状态。该库非常强大,并且具有许多资源,例如缓存,重复,分页
  • >因此,如果您要处理项目中的许多请求,我建议您查看库
  • > 反应

以上就是在实践中反应:处理HTTP请求的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

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