蓝色天空网mbsky.com · 知识 · 实践 · 创造React · 本地阅读预览
教程 / 前端开发 / React

useEffect 进阶

核对 useEffect 依赖变化触发机制、事件处理/useMemo 与 useEffect 的选用边界、setTimeout + cleanup 防抖实现原理,以及博客实时搜索与分类叠加过滤实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

useEffect 依赖触发与事件处理选用边界

当 `useEffect` 的依赖数组包含状态变量(如 `[keyword]`)时,只要该状态发生改变,React 就会在提交渲染后重新执行对应 effect,适合监听状态并自动驱动后续逻辑。本站离线 Chromium 实测受控输入框依次键入 `'H'` 与 `'Hook'`,监听日志准确捕获 `['H', 'Hook']`,同步展示 `当前搜索:Hook`。

在工程选型上,并非所有搜索过滤都需要放进 `useEffect`:若只是本地内存数组按关键词同步筛选,直接写在 `onChange` 事件处理函数或 `useMemo` 派生计算中更简洁且减少一次冗余渲染;`useEffect` 应聚焦于需要与外部系统同步的场景(如发起远程搜索接口请求、持久化写入 `localStorage` 或订阅外部数据源)。

防抖优化(Debounce)原理与 cleanup 清理

若搜索框每次敲击按键都触发远程 API 请求,快速输入会产生大量无效网络开销。防抖(Debounce)的核心思路是“用户停止输入满指定延迟(如 300ms)后再真正执行”:自定义 `useDebounce(value, delay = 300)` 在 `useEffect` 内创建 `setTimeout`,并在返回的清理函数中调用 `clearTimeout(timer)`;只要在 300ms 窗口内有新输入,上一次定时器就会在 effect 重新执行前被取消并重新计时。本站离线 Chromium 使用确定性虚拟时钟实测连续 4 次间隔 60ms 的快速输入(`R` → `Re` → `Rea` → `React`):共取消 `3` 个过期定时器,停顿 200ms 时仍未触发(`midExecutions === []`),跨越 300ms 静默期后仅执行 `1` 次最终搜索 `'React'`。

实战:实时搜索、分类叠加过滤与一键清空

在博客 `HomePage.jsx` 中新增 `keyword` 受控输入状态与 `.search-bar` 样式,将 `filteredArticles` 升级为 `useMemo` 叠加管道:先按 `activeCategory` 过滤分类,再忽略大小写同时匹配文章标题与摘要,并可附带关键词高亮与右侧清空按钮 `✕`。本站离线 Chromium 实测 5 篇文章:输入 `布局` 匹配 2 篇并生成 `<mark>` 高亮(`共 2 篇,搜索「布局」`);输入小写 `hooks` 并切换分类 `React` 实现双条件叠加过滤(`共 2 篇,搜索「hooks」`,命中 `['React 入门完全指南', 'React Hooks 深入解析']`);再切至 `CSS` 分类无交集时展示 `没有找到匹配的文章`;切回 `全部` 后点击 `.clear-btn`,按钮自动隐藏、输入框清空并恢复 `共 5 篇`。

搜索过滤在事件处理函数与 useEffect 中的选用对比

实现方式典型写法适用场景
事件处理 / useMemo 直接派生onChange 中更新并直接或经 useMemo 过滤逻辑纯粹同步、仅受单一或本地状态驱动
useEffect 依赖监听useEffect 依赖 [keyword] 执行异步同步需联动多个外部来源、发起远程搜索接口或防抖请求

离线 Chromium 实测关键词监听、300ms 防抖定时器清理与搜索分类叠加过滤

python · 阅读源码
"""Offline Playwright Chromium lab for React Ch 38: useEffect Keyword Watch, Debounce & Combined Search."""
import json
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")


HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>React Live Search & Debounce Lab</title>
<style>
.search-bar { position: relative; margin-bottom: 16px; max-width: 480px; }
.search-input { width: 100%; padding: 10px 36px 10px 14px; border: 2px solid #eee; border-radius: 8px; }
.clear-btn { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer; }
.category-bar { display: flex; gap: 8px; margin-bottom: 12px; }
.category-bar button.active { background: #1976d2; color: #fff; }
mark { background: #fef08a; padding: 0 2px; }
</style>
</head>
<body>
  <section id="sec-watch">
    <input id="watch-input" type="text" placeholder="监听搜索..." />
    <p id="watch-output">当前搜索:</p>
  </section>

  <section id="sec-blog">
    <div class="search-bar">
      <input id="blog-search" class="search-input" type="text" placeholder="搜索文章标题或摘要..." />
      <span id="clear-btn" class="clear-btn" style="display:none">✕</span>
    </div>
    <div id="cat-bar" class="category-bar"></div>
    <p id="result-info"></p>
    <div id="cards-box"></div>
  </section>

<script>
// 1. Direct useEffect([keyword]) watcher
window.__WATCH_LOG = [];
const watchInput = document.getElementById("watch-input");
const watchOutput = document.getElementById("watch-output");
watchInput.addEventListener("input", (e) => {
  const kw = e.target.value;
  window.__WATCH_LOG.push(kw);
  watchOutput.textContent = `当前搜索:${kw}`;
});

// 2. Deterministic virtual-clock useDebounce(value, 300) verification (zero wall-clock flakiness)
window.runDebounceSimulation = () => {
  let now = 0;
  let nextId = 1;
  const timers = new Map();
  let clearedCount = 0;

  function fakeSetTimeout(fn, delay) {
    const id = nextId++;
    timers.set(id, { fn, runAt: now + delay });
    return id;
  }
  function fakeClearTimeout(id) {
    if (timers.delete(id)) clearedCount += 1;
  }
  function advanceTime(ms) {
    now += ms;
    for (const [id, t] of [...timers.entries()]) {
      if (t.runAt <= now) {
        timers.delete(id);
        t.fn();
      }
    }
  }

  let debouncedKeyword = "";
  let searchExecutions = [];
  let cleanup = null;

  function onKeywordChange(nextValue) {
    if (cleanup) cleanup();
    const timer = fakeSetTimeout(() => {
      debouncedKeyword = nextValue;
      if (debouncedKeyword) searchExecutions.push(debouncedKeyword);
    }, 300);
    cleanup = () => fakeClearTimeout(timer);
  }

  // Rapid typing: 4 keystrokes spaced 60ms apart
  onKeywordChange("R");
  advanceTime(60);
  onKeywordChange("Re");
  advanceTime(60);
  onKeywordChange("Rea");
  advanceTime(60);
  onKeywordChange("React");
  // Still only 200ms after last keystroke -> should not fire yet
  advanceTime(200);
  const midExecutions = [...searchExecutions];
  // Cross 300ms quiet window -> fires once with "React"
  advanceTime(100);

  return {
    clearedCount,
    midExecutions,
    finalExecutions: searchExecutions,
    debouncedKeyword
  };
};

// 3 & 4. Combined category + keyword search + highlight + clear button
const ARTICLES = [
  { id: 1, title: "React 入门完全指南", summary: "从零开始学习 React Hooks,涵盖 useState、useEffect。", category: "React", date: "2024-05-10" },
  { id: 2, title: "JavaScript 异步编程详解", summary: "一文搞懂 Promise、async/await 与微任务队列。", category: "JavaScript", date: "2024-05-08" },
  { id: 3, title: "CSS Grid 布局实战", summary: "用 CSS Grid 轻松实现响应式布局。", category: "CSS", date: "2024-05-05" },
  { id: 4, title: "React Hooks 深入解析", summary: "深入理解自定义 Hook 与状态管理。", category: "React", date: "2024-05-03" },
  { id: 5, title: "Flexbox 布局完全指南", summary: "一文掌握弹性盒模型布局技巧。", category: "CSS", date: "2024-05-01" }
];

let activeCategory = "全部";
let keyword = "";

const searchInput = document.getElementById("blog-search");
const clearBtn = document.getElementById("clear-btn");
const catBar = document.getElementById("cat-bar");
const resultInfo = document.getElementById("result-info");
const cardsBox = document.getElementById("cards-box");

function highlight(text, kw) {
  if (!kw) return text;
  const escaped = kw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return text.replace(new RegExp(`(${escaped})`, "gi"), "<mark>$1</mark>");
}

function renderBlogSearch() {
  clearBtn.style.display = keyword ? "inline" : "none";
  const categories = ["全部", ...new Set(ARTICLES.map((a) => a.category))];
  catBar.innerHTML = "";
  categories.forEach((cat) => {
    const btn = document.createElement("button");
    btn.dataset.cat = cat;
    btn.className = activeCategory === cat ? "active" : "";
    btn.textContent = cat;
    btn.addEventListener("click", () => {
      activeCategory = cat;
      renderBlogSearch();
    });
    catBar.appendChild(btn);
  });

  let filtered = ARTICLES;
  if (activeCategory !== "全部") {
    filtered = filtered.filter((a) => a.category === activeCategory);
  }
  const kw = keyword.trim().toLowerCase();
  if (kw) {
    filtered = filtered.filter(
      (a) => a.title.toLowerCase().includes(kw) || a.summary.toLowerCase().includes(kw)
    );
  }

  resultInfo.textContent = `共 ${filtered.length} 篇${keyword ? `,搜索「${keyword}」` : ""}`;
  cardsBox.innerHTML = "";
  if (filtered.length === 0) {
    const p = document.createElement("p");
    p.className = "empty-tip";
    p.textContent = "没有找到匹配的文章";
    cardsBox.appendChild(p);
    return;
  }
  filtered.forEach((a) => {
    const card = document.createElement("div");
    card.className = "article-card";
    card.innerHTML = `<h3>${highlight(a.title, keyword.trim())}</h3><p>${highlight(a.summary, keyword.trim())}</p>`;
    cardsBox.appendChild(card);
  });
}

searchInput.addEventListener("input", (e) => {
  keyword = e.target.value;
  renderBlogSearch();
});

clearBtn.addEventListener("click", () => {
  keyword = "";
  searchInput.value = "";
  renderBlogSearch();
});

renderBlogSearch();
</script>
</body>
</html>
"""


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)

        # Case 1: useEffect([keyword]) triggers on each keyword change
        page.locator("#watch-input").fill("H")
        page.locator("#watch-input").fill("Hook")
        c1_actual = {
            "watch_log": page.evaluate("() => window.__WATCH_LOG"),
            "watch_output": page.locator("#watch-output").inner_text(),
        }
        c1_expected = {
            "watch_log": ["H", "Hook"],
            "watch_output": "当前搜索:Hook",
        }
        cases.append({
            "name": "effect_dep_keyword_trigger",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        })

        # Case 2: Debounce cleanup cancels intermediate timers and fires once after 300ms
        c2_actual = page.evaluate("() => window.runDebounceSimulation()")
        c2_expected = {
            "clearedCount": 3,
            "midExecutions": [],
            "finalExecutions": ["React"],
            "debouncedKeyword": "React",
        }
        cases.append({
            "name": "debounce_cleanup_timer_reduction",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        })

        # Case 3: Combined category + case-insensitive keyword filter + highlight + empty state
        page.locator("#blog-search").fill("布局")
        layout_info = page.locator("#result-info").inner_text()
        layout_marks = page.locator("#cards-box mark").count()
        page.locator("#blog-search").fill("hooks")
        page.locator('#cat-bar button[data-cat="React"]').click()
        stacked_info = page.locator("#result-info").inner_text()
        stacked_titles = page.locator("#cards-box .article-card h3").all_inner_texts()
        page.locator('#cat-bar button[data-cat="CSS"]').click()
        stacked_empty = page.locator("#cards-box .empty-tip").inner_text()
        c3_actual = {
            "layout_info": layout_info,
            "layout_marks_positive": layout_marks > 0,
            "stacked_info": stacked_info,
            "stacked_titles": stacked_titles,
            "stacked_empty": stacked_empty,
        }
        c3_expected = {
            "layout_info": "共 2 篇,搜索「布局」",
            "layout_marks_positive": True,
            "stacked_info": "共 2 篇,搜索「hooks」",
            "stacked_titles": ["React 入门完全指南", "React Hooks 深入解析"],
            "stacked_empty": "没有找到匹配的文章",
        }
        cases.append({
            "name": "combined_category_and_keyword_filter",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        })

        # Case 4: Clear button visibility & reset
        page.locator('#cat-bar button[data-cat="全部"]').click()
        clear_visible_when_filled = page.locator("#clear-btn").is_visible()
        page.locator("#clear-btn").click()
        clear_visible_after_reset = page.locator("#clear-btn").is_visible()
        reset_info = page.locator("#result-info").inner_text()
        c4_actual = {
            "clear_visible_when_filled": clear_visible_when_filled,
            "clear_visible_after_reset": clear_visible_after_reset,
            "reset_info": reset_info,
            "input_val": page.locator("#blog-search").input_value(),
        }
        c4_expected = {
            "clear_visible_when_filled": True,
            "clear_visible_after_reset": False,
            "reset_info": "共 5 篇",
            "input_val": "",
        }
        cases.append({
            "name": "clear_button_resets_search",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        })

        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对连续输入触发日志、4 次快击取消 3 次旧定时器并仅执行 1 次 'React' 防抖搜索、分类+关键词大小写不敏感叠加过滤与清空按钮重置。
离线 Chromium 实测关键词监听、300ms 防抖定时器清理与搜索分类叠加过滤

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:1e672f79f9579ed8d734020c4a61a7a0fa2d4478a2af1d9ba98ea5b9c3469ae0

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载useEffect 进阶实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:42daa25d064e674c548fb8808a1bd3cfd11dd495bf774cd51657bc9017e8de2e

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 `useDebounce` 实现中,如果忘记返回 `() => clearTimeout(timer)` 清理函数会出现什么问题?

展开参考解答

若缺少 `clearTimeout` 清理,每次按键创建的定时器都会在 300ms 后依次触发,依然会连续更新 `debouncedValue` 并触发同样次数的搜索请求,防抖优化将完全失效,仅变成整体延迟 300ms。

规范与官方依据