react如何获取数据
获取数据的常见方法
在React中获取数据可以通过多种方式实现,根据项目需求和场景选择合适的方法。
使用fetch API
fetch是浏览器原生支持的API,适用于简单的数据请求。以下是一个基本示例:
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error:', error));
}, []);
使用axios库
axios是一个流行的HTTP客户端,提供更简洁的语法和错误处理:
import axios from 'axios';
useEffect(() => {
axios.get('https://api.example.com/data')
.then(response => setData(response.data))
.catch(error => console.error(error));
}, []);
处理异步数据获取
使用async/await语法
在useEffect中直接使用async函数需要额外处理:

useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
setData(response.data);
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
状态管理和数据缓存
使用React Query React Query专门为数据获取和缓存设计:
import { useQuery } from 'react-query';
const { data, isLoading, error } = useQuery('dataKey', () =>
axios.get('https://api.example.com/data').then(res => res.data)
);
使用SWR SWR是另一个轻量级数据获取库:
import useSWR from 'swr';
const { data, error } = useSWR('https://api.example.com/data', url =>
fetch(url).then(res => res.json())
);
高级场景处理
处理分页数据 使用参数控制分页请求:

const [page, setPage] = useState(1);
useEffect(() => {
axios.get(`https://api.example.com/data?page=${page}`)
.then(response => setData(response.data));
}, [page]);
处理表单提交 通过POST请求发送数据:
const handleSubmit = async (formData) => {
try {
const response = await axios.post('https://api.example.com/data', formData);
console.log(response.data);
} catch (error) {
console.error(error);
}
};
错误处理和加载状态
显示加载状态 在请求过程中显示加载指示器:
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
setIsLoading(true);
axios.get('https://api.example.com/data')
.then(response => {
setData(response.data);
setIsLoading(false);
});
}, []);
错误边界处理 使用React的错误边界捕获组件层级错误:
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
logErrorToService(error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
这些方法覆盖了React中数据获取的主要场景,从基础实现到高级应用,开发者可以根据项目复杂度选择合适的方式。






