企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
## 类组件的生命周期 ### 初始化阶段 | 生命周期函数 | 所在阶段 | 描述 | | --- | --- |--- | | constructor | 初始化 | 初始化state、绑定this| | getDerivedStateFromProps | **初始化、更新** | 1. 接收props的值,对props进行操作之后,赋值给state. 2. 代替 componentWillMount 和 componentWillReceiveProps| | componentWillMount | 初始化 | 1. 所有初始化的动作可以放到constructor中 2. 即将被废弃,因为它**不安全**| | render (纯函数) | **初始化、更新** | **不做实际的渲染操作,返回jsx**| | componentDidMount | 初始化 | 1. 初始化 DOM 完成,可以做一些基于 DOM 操作,**DOM 事件监听器** 2. **不是render之后立即执行的,而是渲染完之后,会执行**| ⚠️ 1. constructor 阶段并不是必须的,如果不需要初始化state和绑定this,可以不需要constructor ## render和cmmit * 在组件初始化阶段中,分为 render 阶段和 commit 阶段 ![](https://img.kancloud.cn/ca/f9/caf983fc063824f859e081ca3ee48894_1461x1425.png) ### 更新阶段 * **componentWillReceivedProps** - **不安全的** - 接收props的值,对props进行操作之后,赋值给state。父组件强制渲染的时候,也会触发子组件的这个函数。但是setState时不会触发。 * shouldComponentUpdate - 用于性能优化,决定是否重新渲染组件 * **componentWillUpdate - 不安全的**,getSnapshotBeforeUpdate 代替 * render * getSnapshotBeforeUpdate - 获取更新前 DOM 的状态 * componentDidUpdate - DOM 更新完成 ![](https://img.kancloud.cn/1a/75/1a75aff0645b55839e4a5121346d40d9_1422x1283.png) ### 销毁阶段 * componentWillUnmount - 清除一些可能造成内存泄漏的定时器,延时器,或者是一些事件监听器。 ![](https://img.kancloud.cn/43/e2/43e2a7fb29e936d1e54f34a0fc189908_1387x1674.png) ### 三个阶段生命周期+无状态组件总览图: ![](https://img.kancloud.cn/50/68/50680983e99540dd31c9d69c960d2720_3535x1613.png) ## 函数组件的生命周期 * useEffect - 异步执行,不会阻塞浏览器渲染 * useLayoutEffect - 同步执行的 * componentDidMount相当于 useEffect的第二个参数是空数组 ``` React.useEffect( ( ) => { // 请求数据 , 事件监听 , 操纵dom } , [ ] ) ``` * useEffect 实现 componentWillUnmount ``` React.useEffect( ( ) => { // 请求数据 , 事件监听 , 操纵dom return function componentWillUnmount ( ) { // 解除事件监听器 ,清除定时器,延时器 } } , [ ] ) ``` * useEffect 实现 componentDidUpdate ``` React.useEffect( ( ) => { console.log('组件更新完成:componentDidUpdate ') }) ```