2023-12-07 00:15:18
React.Component 是 React 中用于创建类组件的基类,它提供了一系列生命周期方法和状态管理功能。以下是 React.Component 的基础知识总结:
1. 创建类组件类组件通过继承 React.Component 来定义,必须实现 render() 方法:
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; }}2. 核心特性纯函数:输入(props/state)相同则输出(React 元素)相同。
返旦并回值:必须是 React 元素(JSX)、数组、Fragments、Portals、字符串、数字、布尔值或 null。
禁止修改 state:但可读取 props 和 state 以决定 UI 渲染。
constructor():
初始化 this.state。
绑定事件处理函数的 this 上下文。
注意:必须调用 super(props),否则 this.props 可能为 undefined。
componentDidMount():
调用时机:组件挂载到 DOM 后立即调洞敏用(render() 完成后)。
典型用途:
DOM 操作(如初始化第三方库)。
发起网络请求。
订阅事件(需在 componentWillUnmount 中取消订阅)。
调用时机:组件更新后立即调用(props/state 变化或 forceUpdate 触发)。
典型用途:
比较新旧 props/state 执行副作用(如网络请求)。
操作更新后的 DOM。
注意:必须包裹在条件语句中,避免无限循环。
调用时机:组件卸载及销毁前调用。
典型用途:
清除定时器、取消网络请求。
移除事件监听器。
render() 先执行,返回的 JSX 通过 React.createElement() 生成虚拟 DOM。
React 将虚拟 DOM 渲染到真实 DOM 后,再调用 componentDidMount()。
React.Component 通过生命周期方法和状态管理,为类组件提供了强大的功能。理解 render() 的纯函数特性及生命周期的调用顺序,是高效使用类组件的关键。在现代 React 开发中,函数式组件 + Hooks 已成为主流,但类组件仍适用于特定场景(如错误边界或某些第三方库)。