我正在构建一个 Pokedex (Pokemon Index) 应用程序,使用 React Hook Form 和 React Query,用户可以在其中提交 pokemon 的名称,并且 pokemon 的数据将呈现。我无法检索单个口袋妖怪的数据。当我提交一个口袋妖怪的名字时,我收到一个查询状态 200,但控制台打印一个空对象。请让我知道我做错了什么。
1 回答
3
useQuery 挂钩需要一个返回承诺的函数。所以 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()}>
于 2021-03-19T22:59:13.960 回答