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

同一React组件内能否两次调用useFetch自定义hook发起两次API请求?

问题解答

核心结论

完全可以在同一个组件内多次调用useFetch发起多个独立API请求,这符合React自定义Hook的设计规则:每次调用自定义Hook都会生成完全独立的实例,内部维护的response、error、isLoading等状态互不干扰。

正确使用方式

多次调用时,只需要在解构返回值时对变量重命名,避免命名冲突即可,示例如下:

export const programApi = axios.create({
   baseURL: programApiUrl,
});

// 第一个请求:获取活跃运动类型
const { 
  response: sportTypeRes, 
  isLoading: sportTypeLoading, 
  error: sportTypeError 
} = useFetch({
  api: programApi,
  method: "get",
  url: "/SportsProgram/active_sport_type",
  config: JSON.stringify({ requireAuthentication: true }),
});

// 第二个请求:获取运动赛事列表
const { 
  response: matchListRes, 
  isLoading: matchListLoading, 
  error: matchListError 
} = useFetch({
  api: programApi,
  method: "get",
  url: "/SportsProgram/all_match_list",
  config: JSON.stringify({ requireAuthentication: true }),
});

// 单独处理第一个请求的返回结果
useEffect(() => {
  if (sportTypeRes !== null) {
    // 运动类型相关逻辑
  }
}, [sportTypeRes]);

// 单独处理第二个请求的返回结果
useEffect(() => {
  if (matchListRes !== null) {
    // 赛事列表相关逻辑
  }
}, [matchListRes]);

注意事项

你当前提供的useFetch定义有一处小问题:入参解构没有包含api字段,会导致内部读取api时抛出未定义错误,需要修改入参解构部分:

// 补充接收api参数
export default function useFetch({ api, method, url, data = null, config = null }) {
  // 原有逻辑不变
}

内容的提问来源于stack exchange,提问作者Unknown developer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:48:01