带有动态参数的提供者内部的react-query useQuery

Gar*_*uuk 3 reactjs react-query

我正在使用反应查询,因为它非常强大,但我正在努力尝试在提供程序内的许多组件之间共享我的数据。我想知道这是否是正确的方法。

PostsContext.js

import React, {useState} from 'react';
import { useTemplate } from '../hooks';

export const PostsContext = React.createContext({});

export const PostsProvider = ({ children }) => {
    const fetchTemplate = useTemplate(templateId);
   
    const context = {
        fetchTemplate,
    };

    return <PostsContext.Provider value={context}>{children}</PostsContext.Provider>;
};
Run Code Online (Sandbox Code Playgroud)

使用模板.js

import React from 'react';
import { useQuery } from 'react-query'
import { getTemplateApi } from "../api";

export default function useTemplate(templateId) {
    return useQuery(["templateId", templateId], () => getTemplateApi(templateId), {
        initialData: [],
        enabled:false,
    });
}
Run Code Online (Sandbox Code Playgroud)

然后是我使用上下文的组件

function Posts () {
    const { fetchTemplate } = useContext(PostsContext);

    console.log(fetchTemplate.isLoading)

    fetchTemplate.refetch() <---- how can I refetch with a different templateId?

    return {...}

}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来使用不同的 templateId 动态调用我的钩子,但使用提供程序内部的钩子,这样我就可以在我的应用程序中使用它。这是正确的方法吗?我有深度嵌套的组件,我不想支撑钻头。

TkD*_*odo 9

您不需要 xe2x80x99 需要额外的方式来分发数据,例如反应上下文。只需useQuery在需要的地方使用相同的键进行调用,react query 就会完成剩下的工作。最好将其抽象到自定义挂钩中。

\n

refetch仅当您想使用完全相同的参数重新获取时才应使用。对于更改参数,最好\xe2\x80\x99。使它们成为查询键的一部分,因为只要查询键发生变化,反应查询就会重新获取。

\n

因此,在您的示例中,您只需要使用useTemplate不同的templateId. templateId本身是本地状态(哪个模板已由用户选择),如何使其全局可用取决于您。

\n