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

如何使用useSWR Hook发起多个请求?遇Cannot read properties of null报错

问题分析与解决方案

错误根源

  1. 自定义Hook命名违规:你的Fetch函数是封装SWR的自定义Hook,但未遵循React Hook命名规范(必须以use开头),导致React无法正确识别Hook的生命周期,触发Cannot read properties of null (reading 'destroy')错误。
  2. API请求函数变量错误:FetchApi里将response误写为res,导致res.ok触发未定义错误,中断请求流程。
  3. 错误处理变量引用错误:页面组件中toast.error(error.message)里的error未定义,应对应request1.error或request2.error。

修正后的代码

1. 修正API请求与自定义Hook

async function fetchApi(url) {
  const response = await fetch(url);
  const result = await response.json();
  if (response.ok) { // 修正res为response
    return result;
  }
  throw new Error(result.message);
}

// 自定义Hook必须以use开头
function useFetch(url) {
  const { data, error, isLoading } = useSWR(url, fetchApi);
  return { data, error, isLoading };
}

2. 修正页面组件的多请求实现

export default function Page() {
  const request1 = useFetch("endpoint1");
  const request2 = useFetch("endpoint2");

  // 加载状态处理
  if (request1.isLoading || request2.isLoading) return "Loading...";

  // 错误处理:修正error变量引用
  if (request1.error) {
    toast.error(request1.error.message);
  }
  if (request2.error) {
    toast.error(request2.error.message);
  }

  console.log(request1.data, request2.data);
  
  // 组件必须返回有效JSX,补充返回内容避免警告
  return (
    <div>
      {/* 渲染数据内容 */}
    </div>
  );
}

额外优化建议

  • 如果需要等待两个请求全部完成后再渲染内容,可以结合Promise.all与SWR的mutate方法实现,但上述代码已能满足独立多请求的需求。
  • 可根据业务需求给SWR配置缓存策略(如revalidateOnFocus),调整请求的重验证行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 14:47:31