SWR如何实现不将请求headers/参数纳入缓存key的问题咨询
实现方案
核心逻辑是将需要参与缓存key计算的内容和请求参数拆分,缓存key仅保留url,headers等不参与缓存的参数通过闭包传递给fetcher即可。
步骤1:调整fetcher定义
先确保你的fetcher支持接收url和额外的headers参数,示例如下:
const fetcher = async (url: string, headers: Record<string, string>) => { const response = await fetch(url, { headers }) if (!response.ok) { throw new Error('请求异常') } return response.json() }
步骤2:修改useSWR调用
缓存key仅传入url,headers通过匿名函数的闭包特性传递给fetcher,不会参与缓存key的计算:
const url = `/api/holidays/${ productDetail.subscription.subscriptionId }/potential`; const headers = { [MDA_TEST_USER_HEADER]: `${productDetail.isTestUser}` }; const potentialHolidayStopsResponseWithCredits = useSWR( url, // 缓存key仅用url,headers不参与计算 (url) => fetcher(url, headers), // 闭包传入headers { suspense: true } ).data as PotentialHolidayStopsResponse;
步骤3:mutate调用无需修改
现在缓存key和你调用mutate时传入的url完全匹配,可正常触发全局重验证:
mutate(`/api/holidays/${productDetail.subscription.subscriptionId}/potential`)
扩展说明
如果有其他不需要参与缓存计算的请求参数(比如请求方法、body、凭证配置等),都可以通过上述闭包的方式传递给fetcher,不需要塞进SWR的第一个缓存key参数中。
内容的提问来源于stack exchange,提问作者Jon Flynn
相关产品推荐
相关产品推荐

