如何将自定义React Hook中的fetchConfer函数改为异步函数?
改造自定义React Hook中的fetch函数以支持
.then()调用 问题描述
我编写了如下自定义React Hook:
import axios from "axios"; import Cookies from "js-cookie"; import React from "react"; const useGetConferList= () => { let token = JSON.parse(localStorage.getItem("AuthToken")); const Idperson = JSON.parse(Cookies.get("user")).IdPerson; const [response, setResponse] = React.useState(); const fetchConfer= (datePrensence, idInsurance, timePrensence) => { axios({ method: "post", url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, data: JSON.stringify({ datePrensence, idInsurance, Idperson, searchfield: "", timePrensence: parseInt(timePrensence) * 60, }), }) .then((r) => { setResponse(r.data.Data); }) .catch(() => alert("NetworkError")); }; return { fetchConfer, response }; }; export default useGetConferList;
目前fetchConfer并非异步函数,无法在调用后使用.then()执行后续逻辑。我希望将其改为支持如下调用方式:
fetchConfer(Date, Time, Id).then((r) => { if (search !== "") { window.sessionStorage.setItem( "searchList", JSON.stringify( r.data ) ); } });
请问该如何改造?
改造方案
核心是让fetchConfer返回一个Promise,同时确保外部能拿到需要的响应数据,以下是两种可行的改造方式:
方式一:使用async/await语法(推荐)
import axios from "axios"; import Cookies from "js-cookie"; import React from "react"; const useGetConferList = () => { let token = JSON.parse(localStorage.getItem("AuthToken")); const Idperson = JSON.parse(Cookies.get("user")).IdPerson; const [response, setResponse] = React.useState(); const fetchConfer = async (datePrensence, idInsurance, timePrensence) => { try { const r = await axios({ method: "post", url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, data: JSON.stringify({ datePrensence, idInsurance, Idperson, searchfield: "", timePrensence: parseInt(timePrensence) * 60, }), }); setResponse(r.data.Data); // 返回完整响应对象,满足外部调用时获取r.data的需求 return r; } catch (err) { alert("NetworkError"); // 抛出错误,允许外部通过.catch()捕获处理(可选) throw err; } }; return { fetchConfer, response }; }; export default useGetConferList;
方式二:直接返回axios的Promise
import axios from "axios"; import Cookies from "js-cookie"; import React from "react"; const useGetConferList = () => { let token = JSON.parse(localStorage.getItem("AuthToken")); const Idperson = JSON.parse(Cookies.get("user")).IdPerson; const [response, setResponse] = React.useState(); const fetchConfer = (datePrensence, idInsurance, timePrensence) => { return axios({ method: "post", url: `${process.env.REACT_APP_API_URL_API_GET_ERJASERVICE_LIST}`, headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, data: JSON.stringify({ datePrensence, idInsurance, Idperson, searchfield: "", timePrensence: parseInt(timePrensence) * 60, }), }) .then((r) => { setResponse(r.data.Data); // 返回响应给外部的.then() return r; }) .catch((err) => { alert("NetworkError"); // 抛出错误给外部处理 throw err; }); }; return { fetchConfer, response }; }; export default useGetConferList;
关键改动说明
- 让函数返回Promise:
async函数默认返回Promise,或者直接返回axios调用的结果(axios本身返回Promise),这样外部就能链式调用.then()。 - 传递响应数据:在内部处理完
setResponse后,返回完整的axios响应对象,确保外部.then()中能获取到r.data。 - 错误处理优化:保留错误提示的同时,抛出错误让外部可以选择捕获处理,避免错误被内部吞掉。
改造完成后,你就能按照预期的方式调用fetchConfer并使用.then()执行后续逻辑。
内容的提问来源于stack exchange,提问作者yasxcv
相关产品推荐
相关产品推荐

