欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > React类组件与React Hooks写法对比

React类组件与React Hooks写法对比

2025/4/30 2:54:22 来源:https://blog.csdn.net/ace15824843202/article/details/147514390  浏览:    关键词:React类组件与React Hooks写法对比

React 类组件 vs Hooks 写法对比

分类类组件(Class Components)函数组件 + Hooks
组件定义class Component extends React.Componentconst Component = () => {}
状态管理this.state + this.setState()useState()
生命周期componentDidMount, componentDidUpdateuseEffect(() => {}, [deps])
副作用处理分散在多个生命周期方法中集中在useEffect中,通过依赖数组控制执行时机
上下文(Context)static contextType<Context.Consumer>useContext()
RefscreateRef() + this.myRefuseRef()
方法绑定需要手动绑定this(或在构造函数中绑定)无需绑定,直接使用箭头函数或函数声明
代码结构基于类的继承,逻辑分散在生命周期方法中函数式编程,逻辑按功能聚合,可自定义Hook复用
状态更新this.setState({ key: value })(自动合并对象)setState(newValue)(直接替换状态,需手动合并对象)
路由(v5及以前)通过this.props.history访问路由使用useHistory, useLocation等Hooks
高阶组件(HOC)常用HOC增强组件功能可用HOC,但更推荐自定义Hook替代
性能优化PureComponentshouldComponentUpdateReact.memo + useMemo/useCallback

核心代码示例对比

1. 状态管理
// 类组件
class Counter extends React.Component {state = { count: 0 };increment = () => {this.setState({ count: this.state.count + 1 });};render() {return <button onClick={this.increment}>{this.state.count}</button>;}
}// Hooks
const Counter = () => {const [count, setCount] = useState(0);const increment = () => setCount(count + 1);return <button onClick={increment}>{count}</button>;
};
2. 生命周期/副作用
// 类组件
class DataFetcher extends React.Component {componentDidMount() {fetchData().then(data => this.setState({ data }));}componentDidUpdate(prevProps) {if (prevProps.id !== this.props.id) {fetchData(this.props.id).then(data => this.setState({ data }));}}
}// Hooks
const DataFetcher = ({ id }) => {const [data, setData] = useState(null);useEffect(() => {fetchData(id).then(setData);}, [id]); // 依赖数组控制重新执行
};
3. 上下文(Context)
// 类组件
class UserInfo extends React.Component {static contextType = UserContext;render() {const user = this.context;return <div>{user.name}</div>;}
}// Hooks
const UserInfo = () => {const user = useContext(UserContext);return <div>{user.name}</div>;
};
4. Refs
// 类组件
class InputFocuser extends React.Component {inputRef = React.createRef();focusInput = () => this.inputRef.current.focus();render() {return <input ref={this.inputRef} />;}
}// Hooks
const InputFocuser = () => {const inputRef = useRef(null);const focusInput = () => inputRef.current.focus();return <input ref={inputRef} />;
};

关键总结

  1. 类组件:面向对象风格,强依赖于this和生命周期方法,适合复杂状态逻辑或需要精确控制生命周期的场景。
  2. Hooks:函数式编程风格,逻辑更聚合,避免this绑定问题,代码更简洁,适合逻辑复用和现代React开发。
  3. 迁移建议:新项目优先使用Hooks,旧项目逐步迁移时注意useEffect对生命周期的替代逻辑。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词