我正在开发一个 React JS 项目。我正在使用 React Hooks (功能组件)和React query。
我通常在功能组件中运行/执行查询,如下所示。
const ItemList = (props) => {
let getItemsQuery = useQuery([ 'get-items' ], getItems, {
retry: false,
refetchOnWindowFocus: false
});
// The rest of the code goes here
}
Run Code Online (Sandbox Code Playgroud)
基本上,查询是在组件加载时执行的,因此 API 调用也会进行。
现在,我正在寻找一种只能在单击按钮时执行查询的方法。
return (
<button onClick={() => {
//make the call. The value or value might be overridden when the API call is made when the Call 2 button is clicked
}}>Call 1</button>
<button onClick={() => {
//make the …Run Code Online (Sandbox Code Playgroud) 我正在使用 React Query 并尝试从 JSON 文件内联获取数据(用户)。
我已经使用npm React-query& React-query-devtools 安装了它,并且只有 2 个文件。
App.js:
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query-devtools';
import Users from './Users';
function App() {
return (
<div className="App">
<QueryClientProvider client={QueryClient}>
<Users />
<ReactQueryDevtools initialIsOpen />
</QueryClientProvider>
</div>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
Users.js:
import React from 'react'
import { useQuery } from 'react-query';
const Users = () => {
const { isLoading, isError, data, error } = …Run Code Online (Sandbox Code Playgroud) 我有一个三复选框类型,
当我选中任何框时,我会拨打refetch()电话useEffect()。第一次,我选中所有复选框并返回预期数据!
但对于某些“随机重新更改复选框”的情况,API 返回的数据是“未定义”的,尽管它返回了Postman中的预期数据!
queryKey所以我想我是否需要为我想要获取的每个数据提供一个唯一的
所以我提供了一个随机值“Date.now()”但仍然返回未定义
代码片段
type bodyQuery = {
product_id: number;
values: {};
};
const [fetch, setFetch] = useState<number>();
const [bodyQuery, setBodyQuery] = useState<bodyQuery>({
product_id: item.id,
values: {},
});
const {
data: updatedPrice,
status,
isFetching: loadingPrice,
refetch,
} = useQuery(
['getUpdatedPrice', fetch, bodyQuery],
() => getOptionsPrice(bodyQuery),
{
enabled: false,
},
);
console.log('@bodyQuery: ', bodyQuery);
console.log('@status: ', status);
console.log('@updatedPrice: ', updatedPrice);
useEffect(() => {
if (Object.keys(bodyQuery.values).length > 0) …Run Code Online (Sandbox Code Playgroud) 更新:我现在已经将这个问题作为一个问题提交到了react-query的Github上,你应该在那里关注它。
我有一个非常简单的useQuery:
const refreshable = false // hard coded for the sake of example
const tokenQuery = useQuery('refresh-token', refreshQueryFn, {
enabled: refreshable,
refetchInterval: 1000 * 30,
refetchIntervalInBackground: true,
})
Run Code Online (Sandbox Code Playgroud)
如果这是独立的那么没有问题。一切都会初始化,除非refreshable设置,true否则它会处于休眠状态。
然而,在同一个钩子中我添加了一个观察者......
useEffect(() => {
// Create an observer to watch the query and update its result into state
const observer = new QueryObserver(queryClient, {
queryKey: 'refresh-token',
})
const unsubscribe = observer.subscribe((queryResult) => {
console.log(
'Do something with the token!'
queryResult.data
)
}) …Run Code Online (Sandbox Code Playgroud) 我使用react-query图书馆来获取我的数据。当用户发生变化时,如果自动删除以前的用户数据并获取新数据,我会很高兴。
但这确实不会发生,API 会使用旧的 userId 被调用几次,并且只有在重新关注应用程序 1 或 2 次之后,它才会使用正确的 new 来获取数据userId。这是挂钩:当我在函数中记录一些信息时getData,我可以看到注销后使用旧的 userId 调用了几次。
export default function useData() {
const {user} = useAuth();
const queryClient = useQueryClient();
useEffect(() => {
queryClient.removeQueries('data')
queryClient.invalidateQueries()
}, [user]);
return useQuery('data', () => getData(user!.uid), {
enabled: !!user,
})
}
Run Code Online (Sandbox Code Playgroud)
有谁知道我如何在user更改时删除所有数据?
我的打字稿有类型问题。
我有以下 API:
export const clientAPI ={
//...
getOptions: async (myParam: number) =>
get<{ options: Options[]; courses: any[] }>(`/courses?myParam=${myParam}`)().then((result) => {
localStorage.setItem('result', JSON.stringify(result))
return result
}),
//...
}
Run Code Online (Sandbox Code Playgroud)
假设get方法如下:
const get =
<T>(url: string) =>
() => {
const token = localStorage.getItem('token')
return fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
}).then((res) => parseResponse<T>(res))
}
Run Code Online (Sandbox Code Playgroud)
我调用getOptions如下:
useQuery("result", clientAPIs.getOptions(value as number));
Run Code Online (Sandbox Code Playgroud)
我需要的是将响应放入本地存储中,以便通过动态选择来访问它,这取决于几个事件。当我更改值时,我会调用动态返回选项的 API,因此这就是我需要将它们放入本地存储中的原因。问题是我调用它的方式(上面的最后一个代码)给出了一些类型错误,即使它按照我的意愿编译并实际存储了响应。
错误如下: …
我是按照文档反应查询的新手,我遇到了我正确实施的问题,感谢帮助
错误:
错误:未设置 QueryClient,请使用 QueryClientProvider 设置一个
import { QueryClient, QueryClientProvider, useQuery } from 'react-query'
import axios from 'axios';
const queryClient = new QueryClient()
export default function App() {
const queryInfo =
useQuery('pokemon', () => axios
.get('https://pokeapi.com/api/v2/pokemon')
.then(res => res.data.results))
return (
<QueryClientProvider client={queryClient}>
{queryInfo.data?.map(result => {
return <div key={result.name}>{result.name}</div>
})}
</QueryClientProvider>
)
}
Run Code Online (Sandbox Code Playgroud) 我是菜鸟,使用react query并使用typesript进行反应,我不知道如何解决这个问题: 在函数“onSubmit”中调用React Hook“useQuery”,它既不是React函数组件,也不是自定义React Hook函数。React 组件名称必须以大写字母开头。
export const LoginForm = () => {
const { handleSubmit, control } = useForm<IFormInput>({defaultValues: defaultValues, resolver: yupResolver(schema)});
const onSubmit = ({email, password}: IFormInput) => {
const {data, isLoading, error} = useQuery('loginUser', () => startLogin({email, password}));
console.log(data);
console.log(error);
};
...
...
...
}
Run Code Online (Sandbox Code Playgroud)
export const startLogin = ({email, password}: IFormInput) => (
axios.post(loginEndpoint, {email, password}).then(res => res.data)
);
Run Code Online (Sandbox Code Playgroud) 我正在学习反应查询,以下代码按预期工作,但我收到此警告消息:
React Hook useEffect has missing dependencies: 'code' and 'mutate'. Either include them or remove the dependency array.eslintreact-hooks/exhaustive-deps
Run Code Online (Sandbox Code Playgroud)
但是,如果我在依赖项数组中添加“代码”和“变异”,则会出现无限循环。
React Hook useEffect has missing dependencies: 'code' and 'mutate'. Either include them or remove the dependency array.eslintreact-hooks/exhaustive-deps
Run Code Online (Sandbox Code Playgroud)
我所做的简短解释:
import React, { useState, useEffect } from "react";
import { useMutation } from "react-query";
import * as api from "../api/api";
const getQuery = () => {
const queryParams = new URLSearchParams(window.location.search);
return queryParams.get("code");
};
const Authentication = () => {
const [code] …Run Code Online (Sandbox Code Playgroud) 我用 React Query 制作了一个自定义钩子。我想将 React Query 中名为“data”的值重命名为“customUser”,因此,如果我在 1 个文件中有多个挂钩,则不必担心多个名为“data”的变量。
但是当我将数据值重命名为 customUser 时,它将不起作用。
react-query ×10
reactjs ×10
javascript ×3
react-hooks ×2
typescript ×2
api ×1
axios ×1
next.js ×1
react-native ×1
rename ×1
typeerror ×1