获取数据 in React
获取 API 数据使用 useEffect, handling 加载 and 错误状态, and 数据库.
你将学到
- 基础模式 for 获取数据 in useEffect
- Managing 加载, 成功, and 错误状态
- Preventing race 条件使用 cleanup flags
- 当到 use 数据-获取库 如 React 查询
概念讲解
The Basic Fetch Pattern
The most common way to fetch data in a React component is inside a useEffect that runs when the component mounts or when a relevant dependency changes. You call 获取() (or axios, or any HTTP client), parse the response, and update state with the result. The effect's dependency array typically includes the URL or parameters that determine what data to fetch.
Loading and Error States
A data fetch has three possible outcomes: loading (in progress), success (data received), or error (request failed). You need state for all three. A common pattern is three separate state variables: const [数据, setData] = useState(空), const [加载, setLoading] = useState(真), and const [错误, setError] = useState(空). Set loading to true before the fetch, set it to false after, and set either data or error depending on the outcome. Show a spinner while loading, the data on success, and an error message on failure.
Preventing Race Conditions
If the dependency that triggers the fetch changes while a previous fetch is still in flight, you have a race condition — the older response might arrive after the newer one and overwrite the correct data. Two solutions: use a cancelled flag in the cleanup function (set it to true, and check before setting state), or use an AbortController to actually cancel the in-flight request. The AbortController approach is cleaner because it cancels the network request entirely.
Data-Fetching Libraries
For production applications, consider a data-fetching library like TanStack Query (React Query) or SWR. These libraries handle caching, deduplication, background refetching, optimistic updates, and race conditions automatically. They also provide loading and error states out of the box. For simple one-off fetches, the manual useEffect pattern is fine, but for apps with many data dependencies, a dedicated library dramatically reduces boilerplate and improves UX.
示例代码
import { useState, useEffect } from "react";
function UserList() {
const [users, setUsers] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
// AbortController cancels the request if the component unmounts.
const controller = new AbortController();
async function fetchUsers() {
try {
setLoading(true);
setError(null);
const res = await fetch("/api/users", { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
setUsers(data);
} catch (err) {
if (err.name !== "AbortError") setError(err.message);
} finally {
setLoading(false);
}
}
fetchUsers();
return () => controller.abort(); // Cancel on unmount.
}, []);
if (loading) return <p>Loading users...</p>;
if (error) return <p className="error">Error: {error}</p>;
return (
<ul>
{users.map(u => <li key={u.id}>{u.name} — {u.email}</li>)}
</ul>
);
}
AbortController 取消获取 on unmount, preventing 状态更新 on unmounted 组件. Three 状态 handle 加载, 错误, and 成功.
动手试一试
- HTTP 状态 Codes
理解 HTTP 状态 codes returned 通过你的 API 端点.
- JSON Formatter
格式 and inspect JSON 数据 returned 通过你的 API calls.
常见错误
错误写法
不 handling 加载 and 错误状态
正确做法
每个获取有 three outcomes: 加载, 成功, 错误. Track 所有 three in 状态. Show spinner 虽然加载 and 错误消息 on 失败. 从不 assume 获取总是 succeeds.
错误写法
更新状态之后组件 unmounts
正确做法
Use AbortController or cancelled flag in 副作用 cleanup. 不使用这个, 慢响应 arriving 之后 unmount causes '状态更新 on unmounted 组件' 警告.
练习 获取数据 in React
1 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。