You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在按钮点击事件中正确调用useFetch Hook发起数据请求

问题根源

你触发了React Hook调用规则的报错:所有Hook(包括useFetch)只能在React函数组件/自定义Hook的顶层作用域调用,不能写在点击事件回调、条件判断、循环嵌套这类非顶层作用域里。

实现方案

react-fetch-hook原生支持手动触发请求的模式,不需要把Hook塞进点击回调:通过配置项depends控制请求触发时机,初始设为不触发,点击按钮时更新依赖值即可发起请求。
完整实现代码:

import React, { useState } from 'react';
import useFetch from 'react-fetch-hook';
import { Button } from 'react-bootstrap';

const Component = () => {
  // 控制请求触发的标识,初始为false不发起请求
  const [startFetch, setStartFetch] = useState(false);

  // useFetch放在组件顶层,符合Hook调用规则
  // depends绑定请求触发标识,标识变化时自动发起请求
  const { isLoading, data } = useFetch(
    'https://raw.githubusercontent.com/markmclaren2/sample_json/main/user.json',
    { depends: [startFetch] }
  );

  const handleClick = () => {
    // 点击时翻转标识,触发请求
    setStartFetch(prev => !prev);
  };

  return (
    <div>
      <Button onClick={handleClick} disabled={isLoading}>Load Data</Button>
      <div>
        {!startFetch ? null : isLoading ? 'Loading...' : data ? `Received id: ${data.id}` : null}
      </div>
    </div>
  );
};

export default Component;
关键点说明
  • 不需要额外维护message这类冗余状态,直接根据useFetch返回的加载状态、返回数据渲染内容即可,避免多状态同步问题
  • 加载过程中给按钮加disabled属性,避免用户重复点击触发无效请求
  • 如果需要重复发起相同参数的请求,直接翻转startFetch状态即可,不需要额外写请求逻辑

内容的提问来源于stack exchange,提问作者Abel Tefera Belay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 18:45:36