如何使用 React Query 获取数据?
How to fetch data with React Query?
我正在构建一个 Pokedex(Pokemon 索引)应用程序,使用 React Hook Form 和 React Query,用户可以在其中提交一个 pokemon 的名称,然后将呈现该 pokemon 的数据。我在检索单个口袋妖怪的数据时遇到问题。当我提交一个 pokemon 的名字时,我收到查询状态 200,但控制台打印一个空对象。请让我知道我做错了什么。
useQuery 挂钩需要一个 returns 承诺的函数。所以 handlePokemonFetch 应该是这样的:
const handlePokemonFetch = () => {
return axios(`https://pokeapi.co/api/v2/pokemon/${query}`);
};
正常情况下,react-query 会 运行 挂载组件时查询。如果您不希望出现这种行为,则必须通过设置 enabled: false
来禁用查询,您实际上已经这样做了。如果你想自己触发一个获取,react-query 会给你 refetch
函数:
//notice that we also destructure the refetch function
const { isLoading, isError, data, error, refetch } = useQuery(
"pokemon",
handlePokemonFetch,
{
refetchOnWindowFocus: false,
enabled: false
}
);
//when the data is available save it on the state
if(data) setPokemonCharacter(data);
提交表单时调用该函数:
<form onSubmit={()=>refetch()}>
我正在构建一个 Pokedex(Pokemon 索引)应用程序,使用 React Hook Form 和 React Query,用户可以在其中提交一个 pokemon 的名称,然后将呈现该 pokemon 的数据。我在检索单个口袋妖怪的数据时遇到问题。当我提交一个 pokemon 的名字时,我收到查询状态 200,但控制台打印一个空对象。请让我知道我做错了什么。
useQuery 挂钩需要一个 returns 承诺的函数。所以 handlePokemonFetch 应该是这样的:
const handlePokemonFetch = () => {
return axios(`https://pokeapi.co/api/v2/pokemon/${query}`);
};
正常情况下,react-query 会 运行 挂载组件时查询。如果您不希望出现这种行为,则必须通过设置 enabled: false
来禁用查询,您实际上已经这样做了。如果你想自己触发一个获取,react-query 会给你 refetch
函数:
//notice that we also destructure the refetch function
const { isLoading, isError, data, error, refetch } = useQuery(
"pokemon",
handlePokemonFetch,
{
refetchOnWindowFocus: false,
enabled: false
}
);
//when the data is available save it on the state
if(data) setPokemonCharacter(data);
提交表单时调用该函数:
<form onSubmit={()=>refetch()}>