从 onClick 处理程序触发查询刷新(无效?)

Trigger a query refresh (invalidate?) from onClick handler

反应查询的新手。有一个漂亮的 table 手动刷新按钮。拥有 table 和按钮行的父级拥有查询,我正在通过 props 向下传递一个“重新加载”功能,onClick(向下几个级别)执行:

const MyComponent = () => {
   
   var qKey = ['xyz', foo, bar];
   
   const reload = () => {
        useQueryClient().invalidateQueries(qKey)
   }

   const {isLoading, error, data, isFetching} = useQuery(qKey, async () => {
      /* stuff */
      return response.json()
    }, {keepPreviousData: true});

   return (
      <ActionsBar onRefresh={reload} onClear={foo} onSearch={bar}/>
      <Other stuff...>
   )
}

const ActionBar = (props) => {
   const {onRefresh, onClear, onSearch} = props;

   return (
      <Button onClick={ () => onRefresh()}>Refresh</Button>
      /* other stuff */

报错“reload”调用的是钩子,但不是React函数组件,也不是客户React钩子函数。

我怀疑这是一个 useEffect 问题,但不确定它如何适应上述场景?

const queryClient = useQueryClient();放在MyComponent函数下,

并在重新加载函数中调用 queryClient

const MyComponent = () => {
   const queryClient = useQueryClient()
   var qKey = ['xyz', foo, bar];
   
   const reload = () => {
        queryClient.invalidateQueries(qKey)
   }

   const {isLoading, error, data, isFetching} = useQuery(qKey, async () => {
      /* stuff */
      return response.json()
    }, {keepPreviousData: true});

   return (
      <ActionsBar onRefresh={reload} onClear={foo} onSearch={bar}/>
      <Other stuff...>
   )
}

作为已接受答案的替代方案,您可以传递从 useQuery:

返回的 refetch 方法
   const {isLoading, error, data, isFetching, refetch } = useQuery(qKey, async () => {
      /* stuff */
      return response.json()
    }, {keepPreviousData: true});

   return (
      <ActionsBar onRefresh={refetch} onClear={foo} onSearch={bar}/>
      <Other stuff...>
   )