Axios 与 SWR
约 400 字大约 1 分钟
布欧-Lewyon
2026-05-15
Axios 实例与拦截器
// api/client.ts
import axios from 'axios'
const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_URL || '/api',
timeout: 10000,
})
// 请求拦截器(自动带 Token)
apiClient.interceptors.request.use((config) => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
// 响应拦截器(统一错误处理)
apiClient.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('token')
window.location.href = '/login'
}
return Promise.reject(error)
}
)
export default apiClient// api/users.ts
import apiClient from './client'
export const userApi = {
getUsers: (page: number) =>
apiClient.get('/users', { params: { page } }).then(r => r.data),
getUser: (id: number) =>
apiClient.get(`/users/${id}`).then(r => r.data),
createUser: (data: { name: string; email: string }) =>
apiClient.post('/users', data),
updateUser: (id: number, data: Partial<User>) =>
apiClient.put(`/users/${id}`, data),
}SWR
import useSWR from 'swr'
import useSWRMutation from 'swr/mutation'
const fetcher = (url: string) => fetch(url).then(r => r.json())
function UserProfile({ userId }: { userId: number }) {
const { data, error, isLoading, mutate } = useSWR(
userId ? `/api/users/${userId}` : null, // null 时不请求
fetcher,
{
revalidateOnFocus: false, // 切回标签页不重取
dedupingInterval: 5000, // 5 秒内去重
}
)
// 更新用户(乐观更新)
const { trigger, isMutating } = useSWRMutation(
`/api/users/${userId}`,
(url, { arg }: { arg: { name: string } }) =>
fetch(url, { method: 'PUT', body: JSON.stringify(arg) }),
{
optimisticData: (currentData) => ({
...currentData,
...argument,
}),
}
)
if (isLoading) return <div>Loading...</div>
if (error) return <div>Error</div>
return <div>{data.name}</div>
}Axios vs SWR
| 对比 | Axios | SWR |
|---|---|---|
| 定位 | HTTP 客户端 | 数据获取 Hooks |
| 缓存 | ❌ | ✅ |
| 自动重取 | ❌ | ✅ |
| 乐观更新 | ❌ | ✅ |
| 取消请求 | ✅ | 部分 |
| 关系 | Axios 可作为 SWR 的 fetcher | — |
最佳组合:Axios 做请求 + SWR/React Query 做缓存管理。
小结
- Axios 实例 + 拦截器:统一 Base URL、Token、401 处理。
- SWR:
useSWR获取带缓存的数据,useSWRMutation修改数据。 dedupingInterval去重;revalidateOnFocus控制焦点重取。- SWR 内置缓存 + 自动重取 + 乐观更新,比纯 useEffect 优雅得多。
上一节:React Router v6 下一节:复合组件与 Render Props
