react axios 优化示例

发布于:2025-02-11 ⋅ 阅读:(30) ⋅ 点赞:(0)

使用 axios 是 React 项目中非常常见的 HTTP 请求库。为了提升 axios 在 React 中的性能、可维护性和用户体验,我们可以从 代码组织、请求优化 和 用户体验优化 多个角度进行详细的优化。

一、安装与基础配置

安装 axios

npm install axios

创建 Axios 实例

为了更好地管理请求配置和减少重复代码,建议创建 Axios 实例。

axios.js

import axios from "axios";

const axiosInstance = axios.create({
   
  baseURL: "https://api.example.com", // API 的基础路径
  timeout: 10000, // 请求超时时间
  headers: {
   
    "Content-Type": "application/json",
  },
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
   
    // 可以添加认证 token
    const token = localStorage.getItem("token");
    if (token) {
   
      config.headers.Authorization = `Bearer ${
     token}`;
    }
    return config;
  },
  (error) => {
   
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
   
    return response.data; // 直接返回数据,简化调用
  },
  (error) => {
   
    if (error.response?.status === 401) {
   
      // 处理未授权逻辑
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);
export default axiosInstance;

二、请求优化实践

1. 数据缓存

使用 React Query 或 SWR 实现数据缓存
结合 axios 使用 React Query 或 SWR,自动缓存数据,避免重复请求。

React Query 实现示例:

import {
    useQuery } from "react-query";
import axiosInstance from "./axios";

const fetchData = async () => {
   
  const response = await axiosInstance.get("/data");
  return response;
};

const MyComponent = () => {
   
  const {
    data, error, isLoading } = useQuery("dataKey", fetchData);

  if (isLoading) return 

网站公告

今日签到

点亮在社区的每一天
去签到