import { useCallback, useEffect, useState } from "react"; import { createRoot } from "react-dom/client"; import type { Counts, LabInfo } from "../shared/ipc"; import type { TabId } from "./lib/api"; import { useIpcOnce } from "./hooks/useIpcOnce"; const rendererLoadedAt = Date.now(); let hmrUpdates = 0; if (import.meta.hot) { import.meta.hot.on("vite:afterUpdate", () => { hmrUpdates += 1; }); } const tabs: Array<{ id: TabId; label: string }> = [ { id: "strict", label: "StrictMode" }, { id: "architecture", label: "目录分层" }, { id: "hmr", label: "HMR 边界" }, ]; const emptyCounts: Counts = { counts: {}, idem: { requests: 0, records: 0 }, }; function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } function CountCard({ label, value, hint, testId, }: { label: string; value: number | string; hint: string; testId?: string; }) { return (
{label}
{value}

{hint}

); } function NaiveProbe({ refresh }: { refresh: () => Promise }) { useEffect(() => { void window.api.bump("naive").then(refresh); }, [refresh]); return null; } function RefProbe({ refresh }: { refresh: () => Promise }) { useIpcOnce(() => { void window.api.bump("ref").then(refresh); }); return null; } function IdempotentProbe({ refresh }: { refresh: () => Promise }) { useEffect(() => { void window.api.idem("strict-mount").then(refresh); }, [refresh]); return null; } function ProbeSet({ refresh }: { refresh: () => Promise }) { return ( <> ); } function EventProbe({ refresh }: { refresh: () => Promise }) { return ( ); } function StrictTab({ counts, revision, refresh, }: { counts: Counts; revision: number; refresh: () => Promise; }) { return (

StrictMode 下的副作用

开发模式下 StrictMode 会挂载 → 清理 → 再挂载;写在{" "} useEffect 里的 IPC 会被调用两次。下面四个探针展示问题与三种修法。

事件触发是第三种修法:把副作用从 effect 移到用户动作。
修法 适用 代价
useRef 门闩 确实只需要挂载时执行一次 组件实例重建会重新执行
幂等键 请求可重放,主进程能去重 需要设计稳定的 opId
事件触发 操作本来就由用户发起 不能自动完成初始化
); } function ArchitectureTab() { const tree = `src/ ├── main.tsx # createRoot + StrictMode ├── App.tsx # 页签与探针编排 ├── components/ │ └── (本章把探针留在 App.tsx) ├── hooks/ │ └── useIpcOnce.ts # 只执行一次的 IPC ├── lib/ │ └── api.ts # window.api 类型声明 └── styles.css # 最小原生 CSS,ch15 再上 Tailwind`; return (

渲染进程目录分层

          {tree}
        
为什么先分层再上组件库

入口只管挂载;页面管编排;hooks 管复用;lib 管契约。ch15 的 Tailwind 与 ch16 的组件层只改样式与组件目录,不动 IPC。

CSP 与入口

开发态 Vite 注入样式需要 style-src 'unsafe-inline'; 生产构建输出独立 CSS 后应收紧到 'self',第 46 章复核。

); } function HmrTab({ info }: { info: LabInfo | null }) { return (

HMR 只作用于渲染进程

环境
          {JSON.stringify(
            {
              DEV: import.meta.env.DEV,
              MODE: import.meta.env.MODE,
              protocol: location.protocol,
              electron: info?.electron ?? "—",
              chrome: info?.chrome ?? "—",
              node: info?.node ?? "—",
            },
            null,
            2,
          )}
        

手动验证:保持窗口打开,修改本文件里的任意文案;页面热更新,main PID 不变。 改 main/index.ts 会重启应用,PID 变化。

); } declare global { interface Window { __mountError?: () => void; } } if (import.meta.env.DEV) { window.__mountError = () => { createRoot(document.getElementById("missing-root") as HTMLElement); }; } export default function App() { const [tab, setTab] = useState("strict"); const [counts, setCounts] = useState(emptyCounts); const [info, setInfo] = useState(null); const [revision, setRevision] = useState(0); const refresh = useCallback(async () => { setCounts(await window.api.counts()); }, []); useEffect(() => { void refresh(); void window.api.info().then(setInfo); }, [refresh]); useEffect(() => { window.__setTab = (next) => setTab(next); window.__snapshot = () => ({ tab, counts: counts.counts, idem: counts.idem, }); window.__smoke = async () => { await window.api.reset(); setRevision((value) => value + 1); await sleep(400); const next = await window.api.counts(); setCounts(next); setTab("strict"); return { naive: next.counts.naive ?? 0, ref: next.counts.ref ?? 0, idemRequests: next.idem.requests, idemRecords: next.idem.records, event: next.counts.event ?? 0, }; }; }, [counts, tab]); return (

React 接入实验室

React 19 · StrictMode · HMR · 目录分层

{tab === "strict" && ( )} {tab === "architecture" && } {tab === "hmr" && }
); }