在 React 中引入 Hooks(钩子),主要是为了解决早期 class 组件 在开发和维护中的一些痛点,同时让函数组件拥有更完整的能力。
下面从为什么要用的角度来讲,比较直观:
在 Hooks 出现之前:
props,不能保存状态state、componentDidMount 等Hooks 出现后:
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
✅ 函数组件也能:
useState)useEffect)useContext)this 指向混乱例如:
componentDidMount() {
// 获取数据
}
componentDidUpdate() {
// 获取数据
}
用 Hook 更清晰:
useEffect(() => {
fetchData();
}, []);
以前复用逻辑要靠:
现在可以直接抽 Hook:
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handler = () => setWidth(window.innerWidth);
window.addEventListener('resize', handler);
return () => window.removeEventListener('resize', handler);
}, []);
return width;
}
✅ 任何组件都能直接用:
const width = useWindowWidth();
React 本身强调:
UI = f(state)
Hooks 让组件:
React 官方明确:
React 用 Hooks,是为了让函数组件更强大、代码更简洁、逻辑更好复用,同时减少 class 带来的复杂性。
如果你愿意,我也可以:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。