Hook
一句话解释
Hook 是特殊函数那个 lets 你 'Hook 到' React features 如状态 and lifecycle 从函数组件.
用大白话说
Hook 是函数那个 let 函数组件 use features 那个是 previously 仅 available in 类组件 — 状态, lifecycle 副作用, 上下文, refs, and 更多. 它们开始使用 word use: useState, useEffect, useContext, useRef, etc.
Hooks must follow two rules: (1) only call Hooks at the top level of your component (not inside loops, conditions, or nested functions), and (2) only call Hooks from React function components or custom Hooks.
Hooks were introduced in React 16.8 and fundamentally changed how React code is written. They make logic reusable without changing the component hierarchy — you extract shared logic into a custom Hook and call it from any component.
示例
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => setSeconds(s => s + 1), 1000);
return () => clearInterval(id);
}, []);
return <span>{seconds}s</span>;
}useState and useEffect 是 Hook. 它们 let 这个函数组件持有状态 and 运行边 副作用 (interval) on mount.
常见混淆
容易混淆的对象: lifecycle 方法
关键区别: Lifecycle 方法 (componentDidMount, etc.) belong 到类 组件. Hook (useEffect, etc.) achieve 相同 in 函数组件使用 unified API. 你 cannot use Hook in 类组件.
相关术语
相关资源
相关课程
- 状态
Introduction 到 useState Hook.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。