随笔 - 21  文章 - 0  评论 - 0  阅读 - 2594

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   W-阿飞  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示