《React Hooks"极简教程":用useState/useEffect重构类组件,代
it吧
全部回复
仅看楼主
level 5
如果你还在React类组件的泥潭里挣扎,现在是2025年11月8日晚上9点07分,我要告诉你个好消息:用Hooks重构后的函数组件,代码量直接砍半!本文将用最直白的对比方式,手把手教你用useState+useEffect实现"零this""零生命周期"的清爽代码。文末还有智优达React Hooks状态管理教程中的调试秘籍,助你快速定位状态问题!
一、类组件的3大"反人类设计"1. 状态管理像在解谜jsx复制// 类组件:写个计数器要6行"仪式感"代码 class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; this.handleClick = this.handleClick.bind(this); // 这个this绑得人心累 } handleClick() { this.setState({ count: this.state.count + 1 }); } render() { return <button onClick={this.handleClick}>{this.state.count}</button>; }}2. 生命周期让代码碎成渣
请求数据时要在componentDidMount和componentDidUpdate里复制粘贴相同逻辑,稍不留神就会漏掉componentWillUnmount的清理操作。
3. 逻辑复用就像叠罗汉
用高阶组件(HOC)复用状态?等着看组件树变成"千层饼"吧!
二、Hooks两板斧:useState+useEffect1. useState:一行代码搞定状态jsx复制// Hooks版本:3行搞定计数器function Counter() { const [count, setCount] = useState(0); // 声明+更新函数一气呵成 return <button onClick={() => setCount(count + 1)}>{count}</button>;}2. useEffect:一个钩子管所有副作用jsx复制// 类组件:请求数据要写两个生命周期componentDidMount() { this.fetchData(); }componentDidUpdate(prevProps) { if (prevProps.id !== this.props.id) this.fetchData(); } // Hooks版本:依赖数组自动监听变化 useEffect(() => { fetchData();}, [props.id]); // props.id 变化时自动重新执行 // 清理副作用也简单 useEffect(() => { const timer = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(timer); // 返回清理函数即可 }, []);
三、实战重构:用户卡片组件类组件版(28行)jsx复制class UserCard extends React.Component { constructor(props) { super(props); this.state = { user: null, loading: true }; this.fetchUser = this.fetchUser.bind(this); // 又要绑定this! } componentDidMount() { this.fetchUser(); } fetchUser() { this.setState({ loading: true }); fetch(`/api/user/${this.props.userId}`) .then(res => res.json()) .then(user => this.setState({ user, loading: false })); } render() { if (this.state.loading) return <div>加载中...</div>; return ( <div> <h1>{this.state.user.name}</h1> <button onClick={this.fetchUser}> 刷新</button> </div> ); }}Hooks版(15行,减少46%)jsx复制function UserCard({ userId }) { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); const fetchUser = () => { setLoading(true); fetch(`/api/user/${userId}`) .then(res => res.json()) .then(data => { setUser(data); setLoading(false); }); }; useEffect(() => { fetchUser(); }, [userId]); if (loading) return <div>加载中...</div>; return ( <div> <h1>{user.name}</h1> <button onClick={fetchUser}>刷新</button> </div> );}
四、2025年Hooks调试秘籍
实时状态追踪:用React Developer Tools查看Hooks组件的状态流
依赖项可视化:Chrome插件能高亮useEffect的依赖变化
性能优化:useMemo/useCallback避免不必要的重渲染
更多技巧可参考智优达React Hooks状态管理教程中的《闭包陷阱破解指南》
【行动建议】
今晚:找个类组件用Hooks重写(哪怕只是个按钮)
明天:在团队分享会上炫耀你的"代码减肥成果"
2025年11月08日 13点11分 1
1