[英]react-query - How can I access my queries in multiple components?
I'm just beginning with react query and used it to get a list of books from the server using useQuery in my ListBooks Component我刚从反应查询开始,并使用它在我的 ListBooks 组件中使用 useQuery 从服务器获取书籍列表
const { data, error, isLoading, isError } = useQuery("books", getAllBooks);
How can I access the list of books in any other component?如何访问任何其他组件中的书籍列表?
I've setted the QueryClientProvider like so:我已经像这样设置了 QueryClientProvider:
const queryCache = new QueryCache({
onError: (error) => {
console.log(error);
},
});
const queryClient = new QueryClient({ queryCache });
ReactDOM.render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={preset}>
<BrowserRouter>
<App />
</BrowserRouter>
</ThemeProvider>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</React.StrictMode>,
document.getElementById("root")
);
I'm searching for the equivalent of useSelector in Redux to access the data in the redux store.我正在 Redux 中搜索等效的 useSelector 以访问 redux 存储中的数据。
react-query
manages query caching based on query keys , so in the other component, as long as they're all wrapped inside QueryClientProvider
, you just need to call useQuery
with the matching key ( books
), and react-query
will return the appropriate data for you. react-query
基于查询键管理查询缓存,所以在其他组件中,只要它们都包装在QueryClientProvider
中,您只需使用匹配键( books
)调用useQuery
, react-query
将返回相应的给你的数据。
If you use the same query in multiple places, consider adding a wrapper hook to keep your code clean:如果您在多个地方使用相同的查询,请考虑添加一个包装挂钩以保持您的代码干净:
function useAllBooks() {
return useQuery("books", getAllBooks)
}
function Component1() {
const {...} = useAllBooks()
return (...)
}
function Component2() {
const {...} = useAllBooks()
return (...)
}
You can get access with custom hook useGetFetchQuery
and useQueryClient您可以使用自定义挂钩useGetFetchQuery
和useQueryClient获得访问权限
import { useQueryClient } from "react-query";
export const useGetFetchQuery = (key) => {
const queryClient = useQueryClient();
return queryClient.getQueryData(key);
};
And in component just write like this在组件中就这样写
const data = useGetFetchQuery("key from useQuery or useMutation");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.