React
每次 state 更新都会重新执行函数组件。
在线预览
函数组件执行
标准视图
count:0
ReactDemo 本次挂载已执行:1 次
组件关系与数据流
StateComponentRender / SetupHandler
差异焦点组件函数是 render 过程,不是只运行一次的初始化函数。
实线表示依赖、数据或命令传递,虚线表示事件、回调或清理路径。
flowchart TB
accTitle: React 函数组件重新执行模型
accDescr: 事件调用 setter 后更新 state,React 调度一次新的 render,重新执行 ReactDemo 函数并生成下一棵 UI。
event{{"点击事件"}} --> setter{{"调用 state setter"}}
setter --> state(["count / compact state"])
state --> schedule{{"调度新的 render"}}
schedule --> demo["重新执行 ReactDemo"]
demo -.->|"创建下一次事件处理函数"| event
class state state
class demo component
class event,setter,schedule process
classDef state fill:#ffffff,stroke:#149eca,color:#172033,stroke-width:1.2px
classDef component fill:#e5f6fb,stroke:#149eca,color:#172033,stroke-width:2px,font-weight:600
classDef process fill:#f4fbfd,stroke:#149eca,color:#172033,stroke-width:1.6px
classDef resource fill:#f3f5f8,stroke:#778195,color:#172033,stroke-width:1.4px任意本地 state 更新都会调度 render,ReactDemo 函数从头再次执行。
实际运行源码
import { useRef, useState } from "react";
export function ReactDemo() { const executions = useRef(0); const [count, setCount] = useState(0); const [compact, setCompact] = useState(false);
executions.current += 1;
return ( <div className="demo-stack"> <div className="demo-card"> <span className="demo-tag">函数组件执行</span> <h2>{compact ? "紧凑视图" : "标准视图"}</h2> <p>count:{count}</p> <p>ReactDemo 本次挂载已执行:{executions.current} 次</p> </div> <div className="demo-actions"> <button className="demo-button" type="button" onClick={() => setCount((current) => current + 1)} > count + 1 </button> <button className="demo-button" type="button" onClick={() => setCompact((current) => !current)} > 切换显示模式 </button> </div> </div> );}