Hooks 是 React 16.8 引入的革命性特性,它让函数组件拥有了类组件的能力。以下是 React Hooks 的详细使用指南。
一、基础 Hooks
1. useState - 状态管理
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // 初始值为0
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
{/* 使用函数式更新 */}
<button onClick={() => setCount(prev => prev + 1)}>
Safe Increment
</button>
</div>
);
}
特点:
- 可以多次调用声明多个状态变量
- 状态更新会触发组件重新渲染
- 函数式更新确保获取最新状态
2. useEffect - 副作用处理
import { useState, useEffect } from 'react';
function Example() {
const [data, setData] = useState(null);
// 相当于 componentDidMount 和 componentDidUpdate
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(setData);
}, []); // 空数组表示只在组件挂载时执行
// 监听特定状态变化
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]); // count变化时执行
// 清理函数 (相当于 componentWillUnmount)
useEffect(() => {
const timer = setInterval(() => {
console.log('Timer running');
}, 1000);
return () => clearInterval(timer);
}, []);
}
执行时机:
- 默认在每次渲染后执行
- 可以通过依赖数组控制执行条件
- 清理函数在下一次effect执行前运行