React Query组件复用旧API数据,新数据仅刷新后显示
问题根源及解决方案
核心问题
你遇到的旧数据复用问题,本质是React Query的查询Key没有包含所有影响请求的变量。当前自定义Hook里的查询Key固定为["subscriptionsWithType"],不管chatId、id、userId、type怎么变,React Query都会认为这是同一个查询,直接返回缓存的旧数据,不会触发新的API请求。
修复步骤
修改自定义Hook的查询Key,把所有影响请求结果的参数都加入Key数组:
export const useSubscriptionsWithType = ( chatId: string, id: number, userId: number, type: string ) => { return useQuery( // 将所有可变参数加入查询Key,确保参数变化时触发新查询 ["subscriptionsWithType", chatId, id, userId, type], async () => { const { data } = await api.get( `${chatId}/subscriptions/${id}/${userId}?type=${type}` ); return data; }, { // 修正enabled条件:chatId是字符串,用长度判断更准确 enabled: chatId.length > 0 && userId > 0, refetchOnWindowFocus: false, } ); };
额外优化点
- enabled条件修正:原代码里
chatId > 0的判断有问题,因为chatId是字符串类型,应该用chatId.length > 0或者!!chatId来判断是否有效。 - 状态判断逻辑简化:组件里的状态判断可以合并,避免冗余:
// 只要有一个请求在loading,就显示加载态 if (subscribeStatus === "loading" || unsubscribeStatus === "loading") { console.log("loading"); return <ProfilePageStatsLoading />; } // 只要有一个请求出错,也可以统一处理(根据业务需求调整) if (subscribeStatus === "error" || unsubscribeStatus === "error") { console.log("error"); return <ProfilePageStatsLoading />; } // 两个请求都成功才渲染数据 return ( <ProfilePageStatsWithData user={props.user} subscribed={Object.keys(subscribeData).length} unsubscribed={Object.keys(unsubscribeData).length} /> );
原理说明
React Query通过查询Key来标识不同的查询缓存,当Key数组中的任意元素变化时,React Query会认为这是一个新的查询,自动取消旧请求(如果存在)并发起新请求,同时存储新的缓存数据。
内容的提问来源于stack exchange,提问作者MSmith
相关产品推荐
相关产品推荐

