react如何调用ajax
React 中调用 AJAX 的方法
React 本身不直接提供 AJAX 功能,但可以通过以下方式实现:
使用原生 Fetch API
Fetch API 是浏览器原生支持的现代 AJAX 实现方式。

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
使用 Axios 库
Axios 是一个流行的第三方 HTTP 客户端库,提供更简洁的 API。
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
在 useEffect 中调用
在函数组件中,应在 useEffect 钩子中执行 AJAX 调用。

import React, { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => setData(data));
}, []);
return <div>{data && data.message}</div>;
}
处理加载和错误状态
良好的实践应包括加载状态和错误处理。
function MyComponent() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => {
if (!res.ok) throw new Error('Network response was not ok');
return res.json();
})
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => {
setError(error);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{data.message}</div>;
}
使用自定义 Hook
可以创建可重用的自定义 Hook 来封装 AJAX 逻辑。
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => {
setError(error);
setLoading(false);
});
}, [url]);
return { data, loading, error };
}
function MyComponent() {
const { data, loading, error } = useFetch('https://api.example.com/data');
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{data.message}</div>;
}
注意事项
- 在组件卸载时取消未完成的请求,避免内存泄漏
- 对于复杂应用,考虑使用状态管理工具如 Redux 或 React Query 来管理异步数据
- 在生产环境中添加适当的请求超时处理
- 考虑添加请求取消功能,特别是对于可能长时间运行的请求






