副作用与数据请求
核对 React 副作用概念、useEffect 三种依赖数组写法与死循环风险、fetch 异步加载 posts.json 的四种 UI 状态、cancelled 与事件/定时器清理函数及 Vue 3 生命周期对照。
学完这一章,你能够
- 核对 React 副作用概念、useEffect 三种依赖数组写法与死循环风险、fetch 异步加载 posts.json 的四种 UI 状态、cancelled 与事件/定时器清理函数及 Vue 3 生命周期对照。
副作用概念与 useEffect 三种依赖写法
在 React 中,凡是不直接参与本次 JSX 计算的外部交互都称为副作用(Side Effect),典型包括向服务器请求数据、读写 `localStorage`、设置 `setInterval` 定时器、手动修改 DOM 以及订阅外部事件。副作用不能直接写在组件函数体顶层(否则每次渲染都会重复执行),应统一放入 `useEffect(fn, deps)`。依赖数组决定触发时机:省略第二参数 `useEffect(fn)` 会在每次渲染后执行,若内部调用 `setState` 极易触发无限循环;传入空数组 `useEffect(fn, [])` 仅在首次挂载渲染后执行一次,适合初始数据请求;传入 `[dep]` 则在首次挂载及 `dep` 变化后执行,且再次执行前会先调用上次返回的清理函数。本站离线 Chromium 实测三次渲染(含 1 次无关重渲染与 1 次依赖变化后卸载):无依赖执行 `3` 次、空数组执行 `1` 次、单依赖执行 `2` 次且清理函数精确执行 `2` 次。
fetch 加载 posts.json 与四种异步 UI 状态
将文章数据抽离至静态文件 `public/posts.json` 后,可在 `HomePage` 的 `useEffect(..., [])` 中通过 `fetch('/posts.json')` 异步拉取,并配合 `articles`、`isLoading`、`error` 三个状态完整覆盖加载中、成功、失败(含重试按钮)与空数据四种 UI 状态。同时在 effect 闭包内定义 `let cancelled = false` 并在清理函数中置为 `true`,可避免请求尚未返回时用户离开页面(组件卸载)导致过期的 `setState` 更新。本站离线 Chromium 搭建本地回环 HTTP 服务并以确定性 `threading.Event` 门控慢请求实测:请求挂起期间页面准确展示 `加载中,请稍候...`,放行响应后加载提示消失并渲染 `3` 篇文章(首篇 `React 入门完全指南`);接口返回 HTTP 500 时展示 `加载失败:HTTP 500` 与重试按钮,点击重试后恢复渲染 `3` 篇;接口返回空数组 `[]` 时切换为空态 `该分类下暂无文章`。
清理函数(Cleanup)与 Vue 3 生命周期对照
`useEffect` 回调返回的清理函数会在“组件卸载前”以及“下一次 effect 重新执行前”两个时机运行,用于释放未完成请求(`cancelled` 标记或 `AbortController`)、`removeEventListener` 移除滚动/窗口监听、`clearInterval`/`clearTimeout` 销毁定时器或还原临时 DOM 修改,防止内存泄漏;而一次性的 `localStorage` 写入则无需清理。本站实测组件在门控请求进行中卸载:卸载前派发 `scroll` 事件记录 `1` 次,卸载后再次派发 `scroll` 不再递增、定时器已清理,随后放行在途请求后 `fetchResolvedAfterUnmount === true` 而 `postUnmountWrites === 0`,证明清理守卫完全拦截了卸载后的状态写入。
useEffect 依赖数组三种写法与触发时机
| 调用写法 | 执行时机 | 典型场景与注意事项 |
|---|---|---|
| 省略依赖数组 | 每次组件渲染后均执行 | 极少使用,内部 setState 极易导致死循环 |
| 空依赖数组 [] | 仅在首次挂载渲染后执行一次 | 页面初始化数据拉取、第三方实例初始化 |
| 指定依赖数组 [dep] | 首次渲染后及任一 dep 变化后执行 | 监听状态或路由参数变化并触发响应副作用 |
常见副作用清理需求与清理手段清单
| 副作用类别 | 是否需要清理 | 推荐清理方式 |
|---|---|---|
| 异步网络请求 | 是 | 使用 cancelled 布尔标记或 AbortController 中止 |
| 全局/DOM 事件订阅 | 是 | 在清理函数中调用 removeEventListener |
| setInterval / setTimeout | 是 | 在清理函数中调用 clearInterval / clearTimeout |
| 临时修改 document 标题或类 | 是 | 在清理函数中恢复修改前的初始状态 |
| 持久化写入本地存储 | 否 | 瞬时同步写入,无常驻订阅或句柄,无需清理 |
异步数据请求的四种标准 UI 状态
| 界面状态 | 判定条件 | 推荐界面反馈 |
|---|---|---|
| 加载中(Loading) | isLoading === true | 展示加载提示文字、动画或骨架屏 |
| 请求成功(Success) | isLoading === false && error === null && 数据非空 | 正常渲染文章列表与交互控件 |
| 请求失败(Error) | error !== null | 展示错误详情并提供一键重试入口 |
| 空数据(Empty) | 请求成功但返回空数组 | 展示友好空态提示引导用户 |
Vue 3 生命周期与 React useEffect 对照表
| Vue 3 API | React 等价写法 | 语义说明 |
|---|---|---|
| onMounted | useEffect(fn, []) | 组件首次挂载渲染完成后执行一次 |
| watch(keyword, fn) | useEffect(fn, [keyword]) | 监听指定响应式值变化并触发副作用 |
| onBeforeUnmount | useEffect 返回的 cleanup 函数 | 组件卸载销毁前释放订阅与定时器 |
| 依赖变更前自动清理 | useEffect(() => { fn; return cleanup }, [dep]) | 每次 dep 变更时先清理旧副作用再执行新副作用 |
离线 Chromium 实测 useEffect 依赖模式、事件门控 fetch 四态与卸载清理拦截
"""Offline Playwright Chromium lab for React Ch 37: useEffect Deps, Gated Fetch States & Cleanup."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
POSTS_JSON = json.dumps([
{"id": 1, "title": "React 入门完全指南", "summary": "学习 React Hooks 核心概念", "category": "React", "date": "2024-05-10"},
{"id": 2, "title": "JavaScript 异步编程详解", "summary": "理解 Promise 与事件循环", "category": "JavaScript", "date": "2024-05-08"},
{"id": 3, "title": "CSS Grid 布局实战", "summary": "用 Grid 实现响应式排版", "category": "CSS", "date": "2024-05-05"},
], ensure_ascii=False).encode("utf-8")
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>React useEffect & Fetch Lab</title>
</head>
<body>
<section id="blog-fetch-root"></section>
<section id="cleanup-root"></section>
<script>
// 1. Minimal useEffect dependency modes verifier
window.runEffectDepsTest = () => {
let everyRuns = 0;
let mountRuns = 0;
let depRuns = 0;
let depCleanups = 0;
let prevDep = undefined;
let hasMounted = false;
let depCleanupFn = null;
function renderCycle(depVal) {
// useEffect(fn) - runs every render
everyRuns += 1;
// useEffect(fn, []) - runs once on mount
if (!hasMounted) {
mountRuns += 1;
hasMounted = true;
}
// useEffect(fn, [depVal]) - cleanup before next run when dep changes
if (prevDep === undefined || !Object.is(prevDep, depVal)) {
if (depCleanupFn) depCleanupFn();
depRuns += 1;
depCleanupFn = () => { depCleanups += 1; };
prevDep = depVal;
}
}
renderCycle("A"); // mount
renderCycle("A"); // unrelated re-render (dep unchanged)
renderCycle("B"); // dep changed -> runs previous cleanup then effect
if (depCleanupFn) depCleanupFn(); // unmount cleanup
return { everyRuns, mountRuns, depRuns, depCleanups };
};
// 2 & 3. Real fetch() with 4 UI states: loading, success, error + retry, empty
let currentEndpoint = "/posts-gated.json";
let state = { articles: [], isLoading: true, error: null };
function renderFetchUI() {
const root = document.getElementById("blog-fetch-root");
root.innerHTML = "";
if (state.isLoading) {
const p = document.createElement("p");
p.className = "status-msg";
p.textContent = "加载中,请稍候...";
root.appendChild(p);
return;
}
if (state.error) {
const box = document.createElement("div");
box.className = "status-msg error";
box.innerHTML = `<p class="err-text">加载失败:${state.error}</p>`;
const retry = document.createElement("button");
retry.id = "btn-retry";
retry.textContent = "重试";
retry.addEventListener("click", () => window.loadPosts(currentEndpoint));
box.appendChild(retry);
root.appendChild(box);
return;
}
if (state.articles.length === 0) {
const empty = document.createElement("p");
empty.className = "empty-tip";
empty.textContent = "该分类下暂无文章";
root.appendChild(empty);
return;
}
const grid = document.createElement("div");
grid.className = "article-grid";
state.articles.forEach((a) => {
const card = document.createElement("div");
card.className = "article-card";
card.textContent = a.title;
grid.appendChild(card);
});
root.appendChild(grid);
}
let activeCancel = null;
window.loadPosts = (endpoint) => {
if (activeCancel) activeCancel();
currentEndpoint = endpoint;
let cancelled = false;
activeCancel = () => { cancelled = true; };
state = { articles: [], isLoading: true, error: null };
renderFetchUI();
fetch(endpoint)
.then(async (res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((data) => {
if (!cancelled) {
state = { articles: data, isLoading: false, error: null };
renderFetchUI();
}
})
.catch((err) => {
if (!cancelled) {
state = { articles: [], isLoading: false, error: err.message };
renderFetchUI();
}
});
};
// 4. Unmount cleanup test: cancelled flag + scroll listener + interval timer
window.__CLEANUP_STATS = {
postUnmountWrites: 0,
scrollEvents: 0,
timerCleared: false,
fetchResolvedAfterUnmount: false
};
let unmountHook = null;
window.mountCleanupDemo = () => {
let cancelled = false;
const onScroll = () => { window.__CLEANUP_STATS.scrollEvents += 1; };
window.addEventListener("scroll", onScroll);
const timerId = setInterval(() => {}, 10000);
fetch("/posts-unmount-gated.json")
.then((r) => r.json())
.then(() => {
window.__CLEANUP_STATS.fetchResolvedAfterUnmount = true;
if (!cancelled) {
window.__CLEANUP_STATS.postUnmountWrites += 1;
}
});
unmountHook = () => {
cancelled = true;
window.removeEventListener("scroll", onScroll);
clearInterval(timerId);
window.__CLEANUP_STATS.timerCleared = true;
};
};
window.unmountCleanupDemo = () => {
if (unmountHook) {
unmountHook();
unmountHook = null;
}
};
</script>
</body>
</html>
"""
def main():
gated_started = threading.Event()
gated_release = threading.Event()
unmount_started = threading.Event()
unmount_release = threading.Event()
fail_once = {"should_fail": True}
class LabHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
body = HTML.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif self.path == "/posts-gated.json":
gated_started.set()
gated_release.wait(timeout=10)
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(POSTS_JSON)))
self.end_headers()
self.wfile.write(POSTS_JSON)
elif self.path == "/posts-unmount-gated.json":
unmount_started.set()
unmount_release.wait(timeout=10)
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(POSTS_JSON)))
self.end_headers()
self.wfile.write(POSTS_JSON)
elif self.path == "/posts-retry.json":
if fail_once["should_fail"]:
fail_once["should_fail"] = False
err = b"Internal Error"
self.send_response(500)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(err)))
self.end_headers()
self.wfile.write(err)
else:
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(POSTS_JSON)))
self.end_headers()
self.wfile.write(POSTS_JSON)
elif self.path == "/posts-empty.json":
empty = b"[]"
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(empty)))
self.end_headers()
self.wfile.write(empty)
else:
self.send_response(404)
self.end_headers()
def log_message(self, format, *args):
return
server = ThreadingHTTPServer(("127.0.0.1", 0), LabHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page()
page.goto(f"http://127.0.0.1:{port}/")
# Case 1: useEffect dependency array modes
c1_actual = page.evaluate("() => window.runEffectDepsTest()")
c1_expected = {"everyRuns": 3, "mountRuns": 1, "depRuns": 2, "depCleanups": 2}
cases.append({
"name": "effect_dependency_modes",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
})
# Case 2: Deterministic Event-gated loading state -> success state
page.evaluate("() => window.loadPosts('/posts-gated.json')")
assert gated_started.wait(timeout=5), "Gated fetch did not start"
loading_text = page.locator("#blog-fetch-root .status-msg").inner_text()
gated_release.set()
page.locator("#blog-fetch-root .article-card").first.wait_for(state="visible", timeout=5000)
loaded_titles = page.locator("#blog-fetch-root .article-card").all_inner_texts()
loading_after = page.locator("#blog-fetch-root .status-msg").count()
c2_actual = {
"loading_text": loading_text,
"loaded_count": len(loaded_titles),
"first_title": loaded_titles[0],
"loading_after": loading_after,
}
c2_expected = {
"loading_text": "加载中,请稍候...",
"loaded_count": 3,
"first_title": "React 入门完全指南",
"loading_after": 0,
}
cases.append({
"name": "fetch_loading_gate_and_success",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
})
# Case 3: Error -> Retry recovery -> Empty state
page.evaluate("() => window.loadPosts('/posts-retry.json')")
page.locator("#blog-fetch-root .err-text").wait_for(state="visible", timeout=5000)
err_text = page.locator("#blog-fetch-root .err-text").inner_text()
page.locator("#btn-retry").click()
page.locator("#blog-fetch-root .article-card").first.wait_for(state="visible", timeout=5000)
retry_count = page.locator("#blog-fetch-root .article-card").count()
page.evaluate("() => window.loadPosts('/posts-empty.json')")
page.locator("#blog-fetch-root .empty-tip").wait_for(state="visible", timeout=5000)
empty_text = page.locator("#blog-fetch-root .empty-tip").inner_text()
c3_actual = {
"err_text": err_text,
"retry_count": retry_count,
"empty_text": empty_text,
}
c3_expected = {
"err_text": "加载失败:HTTP 500",
"retry_count": 3,
"empty_text": "该分类下暂无文章",
}
cases.append({
"name": "fetch_error_retry_and_empty_state",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
})
# Case 4: Unmount cleanup prevents cancelled fetch setState + removes scroll listener + clears interval
page.evaluate("() => window.mountCleanupDemo()")
assert unmount_started.wait(timeout=5), "Unmount gated fetch did not start"
page.evaluate("() => window.dispatchEvent(new Event('scroll'))")
page.evaluate("() => window.unmountCleanupDemo()")
page.evaluate("() => window.dispatchEvent(new Event('scroll'))")
unmount_release.set()
page.wait_for_function("() => window.__CLEANUP_STATS.fetchResolvedAfterUnmount === true", timeout=5000)
c4_actual = page.evaluate("() => window.__CLEANUP_STATS")
c4_expected = {
"postUnmountWrites": 0,
"scrollEvents": 1,
"timerCleared": True,
"fetchResolvedAfterUnmount": True,
}
cases.append({
"name": "cleanup_cancelled_listener_and_timer",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
})
browser.close()
finally:
gated_release.set()
unmount_release.set()
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对三种依赖执行次数(3/1/2)、确定性门控下的加载中→3 篇成功、HTTP 500 重试恢复与空态提示,以及卸载后拦截过时写入(postUnmountWrites=0)与监听移除。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:45492817b996206dc341d0f63b412a0e8c378fcc74f0b4c3ed6075c9ef3f73e8
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:b44f660fcb3eeac48e9fa142a001b0a46b39a4d1c8c55f4efc20732e89b2f217
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 `useEffect` 中发起 `fetch` 请求时,为什么要声明 `let cancelled = false` 并在 cleanup 函数里设置 `cancelled = true`?
展开参考解答
因为网络请求是异步的,若请求尚未完成用户就切换页面导致组件卸载,随后响应到达仍执行 `setState` 会触发无效更新甚至竞态覆盖;在清理函数中标记 `cancelled = true`(或调用 `AbortController.abort()`)可确保过时请求结果被安全丢弃。