react类组件生命周期

105 阅读2分钟

生命周期函数(旧)

image.png

说明(特性)

1、这些函数都是回调函数
2、只调用一次

渲染 render

1、使用setState会触发一次render函数
2、页面加载会调用一次

挂载

组件将要挂载:componentWillMount

组件挂载完成:componentDidMount (常用)

componnetDidMount() {
// 写一些页面挂载后,只执行一次的代码
// 一般在这个钩子中做一些初始化的事情,定时器,发网络请求,订阅
}

更新

shouldComponentUpdate

1、这个钩子函数必须返回一个布尔值,如果是true,更新开关打开,如果是false,停止更新,不写返回值
这个钩子函数就是控制组件更新的阀门

componentWillUpdate

componentDidUpdate

componentDidUpdate(preProps, preState) {
可以得到之前的(旧的)props和state
}

卸载

1、卸载组件:unmountComponentAtNode

1、将组建卸载

2、将要卸载:componentWillUnmount(常用)

1、组件卸载之前react会调用这个周期函数
componnetDidMount() {
// 一般在这个钩子中做一些收尾的事情,结束定时器,取消订阅
}

调用顺序

1、挂载
constructor -> componentWillMount -> render -> componentDidMount -> componentWillMount -> unmountComponentAtNode
2、更新
    父组件传入props更新
    1.componnetWillReceiveProps -> shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate
    状态发生变化: 调用setState
    2.setState -> shouldComponentUpdate -> componentWillUpdate -> render -> componentDidUpdate 
    强制更新:不会改变页面状态,就是刷新一下页面,调用forceUpdate()这个方法
    3.forceUpdate -> componentWillUpdate -> render -> componentDidUpdate 

生命周期函数(新)

image.png

变化

1、删除的生命周期
    componentWillMount
    componentWillUpdate
    componnetWillReceiveProps
    这三个钩子函数前面加一个UNSAFE_就可以不报警告,但是尽量不要使用
2、新增的生命周期
    getDriverStateFromProps
    getSnapshotBeforeUpdate

getDriverStateFromProps

此方法适用于一些罕见的情况,即任何情况下state的值都取决于props
派生状态会导致代码冗余,所以慎用

// 使用方法
static getDriverStateFromProps(props, state) {
// 必须要返回一个状态对象或者null
// 什么是状态对象,就是使用state管理的对象
// 可以接受参数(props)
  return props
}
注释:

这个新增的生命周期钩子函数基本不会使用,我们只需要了解那三个常用的钩子函数(componentDidMount,componentWillUnmount,render)就行

getSnapshotBeforeUpdate

在组件更新之前获取dom的一些信息,并且可以传递给

// 使用方法
static getSnapshotBeforeUpdate(props, state) {
// 必须要返回一个状态对象或者null
// 什么是状态对象,就是使用state管理的对象
// 可以接受参数(props)
  return value
}
componentDidUpdate(preProps, preState,snapvalue) {
// 可以得到之前的(旧的)props和state还有得到的快照值
}