React Query GEF AXIOS实例来自React上下文

发布于 2025-02-04 00:05:20 字数 576 浏览 3 评论 0原文

我将与Axios客户端一起使用React-Query。我需要创建一些不受静态AXIOS实例的通用组件,但它们将从React上下文中获得。因此,我可以在多个项目之间分享它们。

目前,我周围有一个包装器,这将为我提供Axios实例。这样:

import { useQuery as useReactQuery } from 'react-query';
import { useAxios } from './axios';

export const useQuery = (queryKey, queryFn, options) => {
  const axios = useAxios();
  return useReactQuery(queryKey, (queryContext) => queryFn(queryContext, axios), options);
};

它有效,但我不喜欢。因为我需要到处导入此包装器而不是原始方法,并且会给项目上的新移民带来头痛(我甚至为此写了Eslint规则)。

有人知道更好的解决方案吗?我找不到更好的东西。

I'm using react-query together with Axios client. I need to create some generic components which are not bound to static Axios instance but they will get instace from React context. So I can share them between multiple projects.

Currently, I have a wrapper around react-query which will provide me Axios instance. Like that:

import { useQuery as useReactQuery } from 'react-query';
import { useAxios } from './axios';

export const useQuery = (queryKey, queryFn, options) => {
  const axios = useAxios();
  return useReactQuery(queryKey, (queryContext) => queryFn(queryContext, axios), options);
};

It works but I don't like it. Because I need to import everywhere this wrapper instead of original method and it causes headaches for newcomers on project (I even wrote eslint rule for that).

Does anybody know a better solution? I was unable to find anything better.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

じ违心 2025-02-11 00:05:20

这似乎是一个很好的解决方案,也是自定义挂钩的目的。新移民可能应该适应当前代码库的操作,如果每个人都使用您的自定义usequery,他们也将使用它。如果没有useaxios,他们将如何提出正确的请求?

您也可以使用现有的ESLINT规则 noflow noreferrer'> no-restruction-imports 直接禁止从react-Query导入usequery

最后,如果没有react-Query,您将如何做不同的事情?您可能还会有自定义挂钩调用useaxios,并产生useffect左右。因此,实际上,自定义挂钩完全可以:)

This seems like a fine solution and also what custom hooks are for. Newcomers should probably adjust to what the current code-base is doing, and if everyone uses your custom useQuery, they will also use it. How would they make a correct request without useAxios ?

You can also use the existing eslint rule no-restricted-imports to disallow directly importing useQuery from react-query.

Lastly, how would you do this differently without react-query? You'd likely also have custom hook that calls useAxios and spawns a useEffect or so. So really, the custom hook is totally fine :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文