React 类组件的生命周期

React 类组件的生命周期可以分成三个阶段:

  1. 挂载(Mounting)阶段:当组件实例被创建并插入 DOM 中时,会调用的方法。

  2. 更新(Updating)阶段:当组件的 props 或 state 发生变化时会调用的方法。

  3. 卸载(Unmounting)阶段:当组件从 DOM 中移除时会调用的方法。

以下是每个阶段典型的生命周期方法:

挂载阶段:

  • constructor()

  • render()

  • componentDidMount()

更新阶段:

  • shouldComponentUpdate()

  • render()

  • getSnapshotBeforeUpdate()

  • componentDidUpdate()

卸载阶段:

  • componentWillUnmount()

示例代码:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    // 初始化状态
    this.state = { counter: 0 };
    console.log('Component is being constructed.');
  }
 
  componentDidMount() {
    // 组件挂载后的操作
    console.log('Component has mounted.');
  }
 
  componentDidUpdate(prevProps, prevState) {
    // 组件更新后的操作
    console.log('Component has updated.');
  }
 
  componentWillUnmount() {
    // 组件卸载前的操作
    console.log('Component is about to unmount.');
  }
 
  render() {
    // 渲染组件
    return (
      <div>
        Counter: {this.state.counter}
      </div>
    );
  }
}

 

posted on 2024-10-23 13:48  W-阿飞  阅读(36)  评论(0)    收藏  举报