**题目:** 请写出 React 组件的生命周期函数分别有哪些,并简单介绍下各自的作用。 ---- **参考答案:** **挂载阶段** 1. `componentWillMount` 组件挂载到 DOM 前 2. `render ` 组件渲染。视图的 JSX 就写在这个函数里 2. `componentDidMount` 组件挂载到 DOM 后。可以访问到 DOM 对象了,一些初始化的 AJAX 请求适合在此阶段发送 **更新阶段** 1. `componentWillReceiveProps` 组件接收到新状态 props 2. `shouldComponentUpdate` 类似于一个拦截器,控制组件是否更新,可以在此阶段一定程度上优化组件,返回 true 表示继续更新,返回 false 则中断组件 render 3. `componentWillUpdate` 调用 render 方法更新组件前 4. `componentDidUpdate` 组件更新后。可以操作更新后组件的 DOM 了 **卸载阶段** 1. `componentWillUnmount` 组件卸载前。可以在这里执行一些清理工作,如清除组件中的定时器等 ---- 上述便是 React v16.0 前的生命周期函数,但在 v16.3 后玩法变了,除了 `shouldComponentUpdate`,其他在`render` 函数之前的所有函数(`componentWillMount`,`componentWillReceiveProps`,`componentWillUpdate`)都被新增加的 `getDerivedStateFromProps` 替代,被替代的生命周期函数会在下一个大版本(也就是React v17) 更新时彻底废弃。React v16.3 还引入了一个新的声明周期函数`getSnapshotBeforeUpdate`,所以最新的生命周期函数列表变成了这样(v16.4): **挂载阶段** 1. `static getDerivedStateFromProps` 在组件创建时和更新 render 方法之前调用,返回一个对象来更新状态,或者返回 null 来不更新任何内容。注意:这是一个静态方法。 2. render 3. `componentDidMount` **更新阶段** 2. `shouldComponentUpdate` 3. `getSnapshotBeforeUpdate` 被调用于render之后,可以读取但无法使用 DOM 的时候,在此阶段可以从 DOM 捕获一些信息(例如滚动位置)。此生命周期返回的任何值都将作为参数传递给 `componentDidUpdate` 4. `componentDidUpdate` **卸载阶段** 1. `componentWillUnmount` > [React v16.3之后的组件生命周期函数](https://zhuanlan.zhihu.com/p/38030418) > [React Fiber是什么](https://zhuanlan.zhihu.com/p/26027085) > [React 生命周期函数图谱](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/)
Activity