⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

React 数据请求 — Fetch API 实战

在 React 中发送 HTTP 请求,处理加载、错误、成功三种状态 · 难度:进阶 · +20XP

React 中请求数据

在 React 组件中,通常在 useEffect 中发起 API 请求。处理三种状态是必须的:

状态UI
loading加载中... / 骨架屏
error错误提示 + 重试按钮
success展示数据

完整请求模式

function PostList() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

useEffect(() => { fetch("/api/posts") .then(r => { if (!r.ok) throw new Error("请求失败"); return r.json(); }) .then(data => setPosts(data)) .catch(e => setError(e.message)) .finally(() => setLoading(false)); }, []);

if (loading) return <div>⏳ 加载中...</div>; if (error) return <div>❌ {error} <button onClick={retry}>重试</button></div>; return <ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>; }

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 85 篇
0 完成
🔥 0