React自定义hook useGetPokemon解构返回值为undefined问题排查
核心原因
你遇到的问题是因为错误地给自定义Hook添加了async声明:
- async函数的返回值会默认被包装为Promise实例,你在
useGetPokemon内部return的{fetchPokemon, pokemon, error}对象,实际是Promise resolve后的值,不是useGetPokemon()调用的直接返回结果。 - 你在组件中调用
useGetPokemon()拿到的是一个Promise对象,对不存在fetchPokemon属性的Promise进行解构,自然得到undefined。
修复方案
直接删除useGetPokemon外层的async关键字即可,外层Hook本身不需要异步声明,异步逻辑已经封装在内部的fetchPokemon函数中。
修复后的自定义Hook代码:
const useGetPokemon = () => { const [pokemon, setPokemon] = useState(null); const [fetchError, setFetchError] = useState(null); const { clearErrors } = useForm(); const fetchPokemon = async (input) => { input = input.toLowerCase(); try { const res = await axios.get(`https://pokeapi.co/api/v2/pokemon/${input}`); const { data } = res; if (data) { setPokemon(data); setFetchError(null); clearErrors(); } } catch (error) { setPokemon(null); setFetchError(error); } }; return { fetchPokemon, pokemon, error: fetchError }; };
修复后组件中调用useGetPokemon()会直接返回你定义的普通对象,解构即可拿到正常的fetchPokemon函数,防抖逻辑也可以正常运行。
补充说明
这是React自定义Hook的基础规则:所有自定义Hook本质都是普通同步函数,内部可以封装异步逻辑,但Hook本身不能被声明为async,否则返回值会被Promise包装,无法直接拿到预期的返回属性。
内容的提问来源于stack exchange,提问作者user8758206
相关产品推荐
相关产品推荐

