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

SWRConfig中共享Fetcher如何同时处理GET与POST请求?

能否用SWRConfig中配置的同一个Fetcher处理GET和POST请求?

可以,但需要调整Fetcher的实现以及自定义Hook的逻辑,让它能识别不同的请求方法并处理对应的参数。具体做法如下:

1. 修改全局Fetcher,支持多请求方法

让Fetcher同时兼容纯URL(默认GET)和带请求配置的对象,以此区分不同请求类型:

const fetcher = async (resource) => {
  let url, options = {};
  
  // 处理两种传参形式:纯URL(默认GET)或包含配置的对象
  if (typeof resource === 'string') {
    url = resource;
    options.method = 'GET';
  } else {
    url = resource.url;
    options.method = resource.method || 'GET';
    // 处理POST请求的body参数
    if (resource.body) {
      options.body = JSON.stringify(resource.body);
      options.headers = {
        'Content-Type': 'application/json',
        ...options.headers
      };
    }
  }

  const res = await fetch(url, options);
  if (!res.ok) throw new Error('请求失败');
  return res.json();
};

2. 更新useRequest Hook,支持传入请求配置

修改useRequest,允许调用时传入请求方法、请求体等配置,将这些信息传递给SWR的key参数:

export const useRequest = (path: string, config?: { method?: string; body?: any }) => {
  if (!path) {
    throw new Error('Path is required');
  }

  const url = `${apiRoute}/api/${path}`;
  // 生成SWR的key:有配置则传对象,无配置则传纯URL
  const swrKey = config ? { url, ...config } : url;

  const { data, mutate, error } = useSWR(swrKey);

  return { data, mutate, error };
};

3. 实际调用示例

  • GET请求:保持原有用法不变
const { data, isLoading } = useRequest('data');
  • POST请求:传入method和body参数,通过mutate触发请求
const { mutate } = useRequest('submit-form', { 
  method: 'POST', 
  body: { username: 'junray', email: 'test@example.com' } 
});

// 在需要提交的时机调用mutate
const handleSubmit = async () => {
  try {
    await mutate();
    // 提交成功后的逻辑,比如重新获取数据更新缓存
    await mutate('data');
  } catch (err) {
    console.error('提交失败', err);
  }
};

需要注意的是,SWR核心设计是为了数据获取(GET场景)优化缓存,但通过上述方式可以复用同一个Fetcher处理POST等写操作,同时借助mutate方法完成数据更新与缓存同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:25:20