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

React Query中refetch方法在TypeScript下的类型标注问题求助

React Query refetch方法的类型标注问题

在React应用中使用React Query处理异步请求时,遇到了refetch方法的类型标注问题。

组件代码示例

// 组件中useQuery的定义方式
...
const { data: notes = [], isLoading, isError, refetch } = useQuery<INotesList[]>(
    'notes',
    fetchNotes,
    {retry: 1, refetchOnWindowFocus: false, keepPreviousData: true})
...

// 按钮点击事件中使用refetch
<button
    onClick={(e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => refetch(e)}>
    Retry
</button>

遇到的错误

TS2559: Type 'MouseEvent ' has no properties in common with type 'RefetchOptions & RefetchQueryFilters '.

如果直接写成onClick={refetch},代码能正常运行,但缺少显式类型标注。想知道是否可以为此类事件添加显式类型标注?


解决方案

你不需要把鼠标事件传递给refetch——refetch接收的是React Query的重配参数(RefetchOptions & RefetchQueryFilters),和React的鼠标事件完全无关。

要添加显式类型标注,有两种可行方式:

  1. 明确标注事件处理函数类型
    声明点击事件的类型,内部调用refetch时不传无效的事件参数:

    <button
        onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
            // 如需阻止默认行为可添加,不需要则直接调用refetch
            // e.preventDefault();
            refetch(); // 使用默认配置重取数据
        }}>
        Retry
    </button>
    
  2. 给refetch显式标注类型
    如果你想直接把refetch绑定到onClick,可以手动给refetch声明类型(React Query本身会自动推导类型,这里是为了满足显式标注的需求):

    import { RefetchOptions, RefetchQueryFilters } from '@tanstack/react-query';
    
    // 解构时先取出refetch
    const { 
        data: notes = [], 
        isLoading, 
        isError, 
        refetch: refetchNotes 
    } = useQuery<INotesList[]>(
        'notes',
        fetchNotes,
        {retry: 1, refetchOnWindowFocus: false, keepPreviousData: true}
    );
    
    // 给refetch变量标注类型
    const refetch: (options?: RefetchOptions & RefetchQueryFilters<INotesList[]>) => Promise<{ data: INotesList[] | undefined }> = refetchNotes;
    
    // 直接绑定到onClick
    <button onClick={refetch}>Retry</button>
    

补充说明

直接写onClick={refetch}能运行的原因是:React的onClick会传递事件参数,但refetch的参数是可选的,TS允许函数接收额外参数(只要函数定义的参数数量不超过调用时传递的),所以不会报错。但这属于隐式兼容,正确的做法是避免把事件参数传给refetch,防止后续类型变动引发问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:32:28