React 中 axios 请求库的优化与问题解决
这段代码中存在一些问题:\n\n1. 在拦截器中使用了useSelector hook,但是在拦截器中无法使用hook。拦截器是在请求发出之前执行的,而hook只能在组件函数组件中使用。如果需要在拦截器中获取redux的状态,可以通过其他方式获取。\n\n2. 在拦截器中使用了Toast组件,但是在拦截器中无法直接使用组件。拦截器是在请求发出之前执行的,无法直接渲染组件。如果需要在拦截器中进行提示操作,可以通过其他方式实现,例如使用全局的提示组件。\n\n3. request函数的类型定义有问题。request函数应该返回一个Promise,而不是instance.request的返回值。可以将request函数的返回类型设置为Promise<T>。\n\n以下是修改后的代码:\n\njsx\nimport axios, { AxiosInstance, AxiosRequestConfig } from 'axios'\nimport NProgress from 'nprogress'\nimport 'nprogress/nprogress.css'\nimport { useSelector } from 'react-redux'\nimport { IResponseData } from '../types/user'\n\n// 配置请求的根路径\nconst instance: AxiosInstance = axios.create({\n baseURL: 'https://consult-api.itheima.net/',\n timeout: 5000,\n})\n\n// 在请求拦截器中显示进度条 NProgress.start()\ninstance.interceptors.request.use(\n function (config: AxiosRequestConfig) {\n NProgress.start()\n const { userinfo } = useSelector((state: any) => state.counter)\n if (userinfo?.token && config.headers) {\n config.headers['Authorization'] = `Bearer ${userinfo?.token}`\n }\n return config\n },\n function (error) {\n return Promise.reject(error)\n }\n)\n\n// 在响应拦截器中隐藏进度条 NProgress.done()\ninstance.interceptors.response.use(\n function (response) {\n NProgress.done()\n const { message, code } = response.data\n if (code !== 10000) {\n // 这里无法直接使用组件,需要通过其他方式实现提示\n console.error(message) // 使用console打印错误信息\n return Promise.reject(response.data)\n }\n return response.data\n },\n function (error) {\n return Promise.reject(error)\n }\n)\n\nconst request = <T>(\n url: string,\n method: string,\n submitData?: object\n): Promise<T> => {\n return new Promise<T>((resolve, reject) => {\n instance\n .request<IResponseData<T>>({\n url,\n method,\n [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData,\n })\n .then((response) => {\n resolve(response.data)\n })\n .catch((error) => {\n reject(error)\n })\n })\n}\n\nexport default request\n\n\n请注意,修改后的代码仅修复了已知的问题,如果还有其他问题,请提供更详细的信息。
原文地址: https://www.cveoy.top/t/topic/qCHU 著作权归作者所有。请勿转载和采集!