概要
例子
代码
import {Component} from 'react'
import { unmountComponentAtNode } from 'react-dom';
export default class LifeCylce extends Component {
constructor(props){
super(props)
console.log("constructor 执行了")
}
// 不推荐使用,官方推荐用constructor和componentDidMount来进行代替
// componentWillMount(){
// console.log("组件将要加载~");
// }
componentDidMount(){
console.log("组件加载完毕~");
}
// 不推荐使用,官方推荐用getSnapshotBeforeUpdate或
// componentWillUpdate(){
// console.log("组件将要更新~");
// }
getSnapshotBeforeUpdate(){
console.log("组件将要更新~");
}
componentDidUpdate(){
console.log("组件更新完毕~");
}
componentDidMount(){
console.log("组件更新完毕~");
}
componentWillUnmount(){
console.log("组件将要被移除~");
}
render(){
console.log("执行了render");
return (
<>
<h2>组件生命周期</h2>
</>
)
}
}
效果
执行两次constructor问题
- 开发(dev)环境下,渲染使用的是严格模式(strict mode),严格模式是通过调用两次constructor函数来检测意外的副作用,通过此方式将一些隐藏的比较深的副作用放大
- 生产(production)环境不会出现此情况 博客
知识点
官网 点击,所谓声明周期钩子函数,也就是说当组件从实例化到卸载的时候,所触发的函数调用
挂载
当组件进行挂载的时候,会依次触发以下函数的调用
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
更新
当组件更新时,也就是当
state
或者props
变化的时候,会依次触发一下函数
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
卸载
一般,当进行路由的跳转,或者页面的刷新的时候,组件会自行卸载
componentWillUnmount()
图示
想要看比较全的组件生命周期,点击
注意
过时的钩子
从 React v16.3 开始,有 3 个生命周期方法被标记为过时:componentWillMount()
、componentWillReceiveProps()
和 componentWillUpdate()
目前它们仍然有效,但不建议在新代码中使用,官方为它们新增了一个以“UNSAFE_
”作为前缀的别名
新增的钩子
React v16 新增了两个生命周期方法,如下所列
static getDerivedStateFromProps(nextProps, prevState)
- 静态方法
getDerivedStateFromProps()
用来替代componentWillReceiveProps()
- 包含两个参数:
nextProps
和prevState
,分别表示新的 props 和旧的 state - 如果返回一个对象,那么更新 state;如果返回 null,那么就不更新 state
- 静态方法
getSnapshotBeforeUpdate(prevProps, prevState)
getSnapshotBeforeUpdate()
方法用来替代componentWillUpdate()
- 包含两个参数:prevProps 和 prevState,分别表示旧的 props和旧的 state
- 返回值会成为
componentDidUpdate()
的第三个参数
应用场景
- 一般在组件将要写在的时候,我们用来移除定时器,接触监听等