在函数内部使用 RTK-Query 钩子的方法? [英] Approaches for using RTK-Query hooks inside functions?

查看:21
本文介绍了在函数内部使用 RTK-Query 钩子的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地使用 Axios 编写了我的应用程序来获取内容.截至目前,它已设置为在发生某些事件时获取内容(例如单击提交按钮).不过,我正在试验 Redux 的 RTK-Query 解决方案.这个包生成钩子,在他们的示例中,他们提供了简单的组件级调用挂载钩子的例子.

I've successfully written my application using Axios to fetch content. As of now, it's set up to fetch content when certain events happen (like the submit button has been clicked.) However, I'm experimenting with Redux's RTK-Query solution. This package generates hooks and in their examples, they provide simple component-level examples that call the hooks on mount.

我如何利用这些 rtk-hooks(以及一般的钩子),以便将它们与诸如 onClickonSubmit 和条件事件之类的行为联系起来? 我知道这与 rules-of-hooks 指南,但我无法想象 RTK-Query 会如此受限,以至于只允许组件级 onMount API 调用.

How can I leverage these rtk-hooks (and hooks in general) so I can tie them to behaviors like onClick, onSubmit, and conditional events? I'm aware this conflicts with the rules-of-hooks guidelines, but I can't imagine RTK-Query would be so limited as to only allow component-level onMount API calls.

我正在阅读一些相关文章,同时我试图弄清楚这一点/等待一个有用的例子:

some related articles I'm reading while I try to figure this out / wait for a helpful example:

  • https://blog.logrocket.com/react-hooks-frustrations/
  • https://redux-toolkit.js.org/rtk-query/usage/usage-without-react-hooks
  • 第二篇文章似乎有些相关,但我觉得它离路径太远了,并且正在质疑是否值得安装 rtk-query.我不妨只使用 axios,因为它可以在我的组件和逻辑中的任何地方使用.有人可以教我如何解决这个问题吗?我是 rtk-query 的新手,它看起来很酷,但它的实现方法似乎也很严格.

    The second article seems somewhat relevant but I feel like its beating too far off the path and is making question if it's even worth having rtk-query installed. I might as well just use axios since it can be used anywhere in my components and logic. Can someone educate me on how to approach this problem? I'm new to rtk-query, it seems really cool but it also seems really restrictive in its implementation approaches.

    import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
    
    const apiEndpoint = 'http://localhost:5000';
    
    export const myApi = createApi({
      reducerPath: 'myApi',
      baseQuery: fetchBaseQuery({ baseUrl: apiEndpoint }),
      endpoints: builder => ({
        getFileById: builder.query<any, { id: string; fileId: string }>({
          query: arg => {
            const { id, fileId } = arg;
            return `/service/${id}/files/${fileId}`;
          },
        }),
      }),
    });
    
    // RTK Query will automatically generate hooks for each endpoint query
    export const { useGetFileByIdQuery } = myApi;
    

    使用 axios 的通用示例:

    const handleSubmit = async (): Promise<void> => {
        try {
          const getResponse = await axios.get('my-endpoint/abc/123');
        }
        catch (e) {
         ...
        }
    }
    

    推荐答案

    如果你使用查询,你会使用本地组件状态来设置查询参数

    If you use a query, you would use local component state to set the query parameter

    const [myState, setState] = useState(skipToken) // initialize with skipToken to skip at first
    const result = useMyQuery(myState)
    

    然后在您的点击处理程序中设置状态

    and in your click handler you then set the state

    const changePage = () => {
      setState(5)
    }
    

    不过,在您的情况下,您有一个表单提交,听起来您想使用变异",而不是查询.突变的意义在于,您对长期的结果并不真正感兴趣,而是希望通过发送数据来触发服务器上的更改.

    In your case though, you have a form submit and that sounds you want to use a "mutation", not a query. The point of mutations is that you are not really interested in the result long-term, but rather want to trigger a change on the server by sending data.

    const [trigger, result] = useMyMutation()
    

    这将被称为

    const handleSubmit = () => {
      trigger(someValue)
    }
    

    这篇关于在函数内部使用 RTK-Query 钩子的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆