react如何接接口
React 中接入接口的常见方法
使用 fetch API 发起 HTTP 请求fetch 是浏览器原生支持的 API,无需额外安装库。发起 GET 请求的示例代码如下:
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 中调用接口
React 函数组件中通常在 useEffect 钩子中发起异步请求,避免直接放在渲染函数中:
import React, { useState, useEffect } from 'react';
function DataComponent() {
const [data, setData] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => setData(response.data));
}, []);
return <div>{data && data.map(item => <p key={item.id}>{item.name}</p>)}</div>;
}
处理加载和错误状态
完整的接口调用应包含加载状态和错误处理:
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => {
setData(response.data);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
使用自定义 Hook 封装请求逻辑
将接口调用逻辑封装成可复用的自定义 Hook:
function useApi(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
});
}, [url]);
return { data, loading };
}
// 使用示例
function MyComponent() {
const { data, loading } = useApi('https://api.example.com/data');
// ...
}
POST 请求示例
发送 POST 请求时需指定方法和请求体:
axios.post('https://api.example.com/data', {
name: 'New Item',
value: 123
})
.then(response => console.log(response.data));
处理 CORS 问题
如果接口存在跨域问题,需在后端配置 CORS 或通过代理解决。开发时可配置 package.json 添加代理:
"proxy": "http://localhost:5000"






