译零 TransZero · TanStack Query 中文文档
主站

默认查询函数

更新于 2026-11-02 Preact 查看英文原文 ↗

如果你出于任何原因希望为整个应用共享同一个查询函数,并仅通过查询键来标识它应拉取的内容,你可以通过向 TanStack Query 提供一个 默认查询函数 来实现:

TypeScript
1// Define a default query function that will receive the query key2const defaultQueryFn = async ({ queryKey }) => {3  const { data } = await axios.get(4    `https://jsonplaceholder.typicode.com${queryKey[0]}`,5  )6  return data7}8 9// provide the default query function to your app with defaultOptions10const queryClient = new QueryClient({11  defaultOptions: {12    queries: {13      queryFn: defaultQueryFn,14    },15  },16})17 18function App() {19  return (20    <QueryClientProvider client={queryClient}>21      <YourApp />22    </QueryClientProvider>23  )24}25 26// All you have to do now is pass a key!27function Posts() {28  const { status, data, error, isFetching } = useQuery({ queryKey: ['/posts'] })29 30  // ...31}32 33// You can even leave out the queryFn and just go straight into options34function Post({ postId }) {35  const { status, data, error, isFetching } = useQuery({36    queryKey: [`/posts/${postId}`],37    enabled: !!postId,38  })39 40  // ...41}

如果你需要覆盖默认的 queryFn,只需像平常一样提供你自己的 queryFn 即可。