react如何调用ajax
使用 Fetch API 调用 AJAX
Fetch API 是现代浏览器原生支持的 AJAX 调用方式,无需额外安装库。
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
在 React 组件中使用时,通常结合 useEffect 钩子:
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(json => setData(json));
}, []);
return <div>{data && data.message}</div>;
}
使用 Axios 调用 AJAX
Axios 是流行的第三方 HTTP 客户端,需要先安装:
npm install axios
基础用法:
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
在 React 组件中的完整示例:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
axios.get('https://api.example.com/users')
.then(res => setUsers(res.data))
.catch(err => console.log(err));
}, []);
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
处理异步操作的现代方式
使用 async/await 语法可以更清晰地处理异步操作:
useEffect(() => {
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
setData(response.data);
} catch (error) {
console.error(error);
}
}
fetchData();
}, []);
错误处理最佳实践
完整的错误处理应包括网络错误和业务逻辑错误:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.error) {
throw new Error(data.error);
}
setData(data);
})
.catch(error => {
setError(error.message);
});
取消请求
对于可能被卸载的组件,应取消未完成的请求:
useEffect(() => {
const controller = new AbortController();
fetch('https://api.example.com/data', { signal: controller.signal })
.then(res => res.json())
.then(setData);
return () => controller.abort();
}, []);
Axios 的取消方式:
useEffect(() => {
const source = axios.CancelToken.source();
axios.get('https://api.example.com/data', {
cancelToken: source.token
}).then(res => setData(res.data));
return () => source.cancel('Component unmounted');
}, []);






