React.Component基础知识

React.Component基础知识
最新回答
一生玺爱

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. 核心特性
  • 状态管理:通过 this.state 初始化和管理内部状态。
  • 生命周期纳迟枝:提供挂载、更新、卸载等阶段的钩子函数。
  • render() 方法

    纯函数:输入(props/state)相同则输出(React 元素)相同。

    返旦并回值:必须是 React 元素(JSX)、数组、Fragments、Portals、字符串、数字、布尔值或 null。

    禁止修改 state:但可读取 props 和 state 以决定 UI 渲染。

3. 生命周期方法挂载阶段
  • constructor()

    初始化 this.state。

    绑定事件处理函数的 this 上下文。

    注意:必须调用 super(props),否则 this.props 可能为 undefined。

  • componentDidMount()

    调用时机:组件挂载到 DOM 后立即调洞敏用(render() 完成后)。

    典型用途

    DOM 操作(如初始化第三方库)。

    发起网络请求。

    订阅事件(需在 componentWillUnmount 中取消订阅)。

更新阶段
  • componentDidUpdate(prevProps, prevState, snapshot)

    调用时机:组件更新后立即调用(props/state 变化或 forceUpdate 触发)。

    典型用途

    比较新旧 props/state 执行副作用(如网络请求)。

    操作更新后的 DOM。

    注意:必须包裹在条件语句中,避免无限循环。

卸载阶段
  • componentWillUnmount()

    调用时机:组件卸载及销毁前调用。

    典型用途

    清除定时器、取消网络请求。

    移除事件监听器。

4. 关键注意事项
  • render() 与 componentDidMount() 的时序

    render() 先执行,返回的 JSX 通过 React.createElement() 生成虚拟 DOM。

    React 将虚拟 DOM 渲染到真实 DOM 后,再调用 componentDidMount()。

  • 异步性:componentDidMount 不会在 render() 完成后立即同步调用,而是由 React 的渲染流程异步触发。
5. 与函数式组件对比
  • 类组件:适合需要状态、生命周期或复杂逻辑的场景。
  • 函数式组件:通过 Hooks(如 useState、useEffect)实现类似功能,代码更简洁。
示例代码class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } componentDidMount() { console.log("组件已挂载"); this.timer = setInterval(() => { this.setState({ count: this.state.count + 1 }); }, 1000); } componentDidUpdate(prevProps, prevState) { if (prevState.count !== this.state.count) { console.log("计数更新:", this.state.count); } } componentWillUnmount() { clearInterval(this.timer); console.log("组件将卸载"); } render() { return <div>当前计数: {this.state.count}</div>; }}总结

React.Component 通过生命周期方法和状态管理,为类组件提供了强大的功能。理解 render() 的纯函数特性及生命周期的调用顺序,是高效使用类组件的关键。在现代 React 开发中,函数式组件 + Hooks 已成为主流,但类组件仍适用于特定场景(如错误边界或某些第三方库)。