一. 挂载阶段
(1) constructor
- this.props = props
- 初始化数据
- 非箭头函数的 this 指向
- 只执行一次 ( 不要在这里写三元表达式 )
(2) static getDerivedStateFromProps
- 参数 nextProps,PrevState
- 可以修改一次state的值, 不会重新渲染
- 必须有返回值(null/{ 在这里可以修改state值,只能修改一次 })
- 这个钩子函数是静态方法,没有 this
(3) render
- 返回 jsx 结构, React.createElement 渲染为vdom
(4) componentDidMount
- 第三方类库的实例化
- 有真实 dom, 可以进行 dom 操作
- ajax 数据请求
- 只执行一次
- 在这里修改 state 会触发 getDerivedStateFromProps & render
弃用:
UNSAFE_componentWillMount
二. 更新阶段
(1) static getDerivedStateFromProps
- 和初始化阶段共用
(2) shouleComponentUpdate
- 两个参数, nextProps nextState
- 组件是否更新, 必须有返回值
- 返回布尔值, true 表示更新
- 性能优化, 防止组件无意义渲染
- 将 this.props 与 nextProps 以及 this.state 与 nextState 进行比较来决定是否返回 false,来减少重新渲染
(3) render
- 和初始化阶段的 render 共用
(4) getSnapshotBeforeUpdate
- 两个参数, prevProps prevState
- 必须有返回值, 返回值作为 componentDidupdate 的第三个参数
(5) componentDidupdate
- 三个参数 prevProps prevState snapShot
弃用:
- UNSAFE_componentWillUpdate
- UNSAFE_componentWillReceiveProps
三. 卸载阶段
(1) componentWillUnmount
- 清除定时器
- 解绑事件侦听
- ...
四. 错误处理阶段
(1) componentDidCatch(error, info)
- 参数 error —— 抛出的错误
- 参数 info —— 带有 componentStack key 的对象,其中包含有关组件引发错误的栈信息
- 监听子组件的错误,然后用降级UI来代替崩溃组件树
- static getDerivedStateFromError , 监听子组件的错误,然后更新state , 记录错误栈信息
import React, { Component,logComponentStackToMyService } from 'react'
export default class LayOut extends Component {
constructor(props) {
super(props)
this.state = {
f: false
}
}
static getDerivedStateFromError () {
// 当子组件也就是我们Home组件发生问题时,这个钩子触发,然后更新state
return {
f: true
}
}
componentDidCatch( err,info ) {
// 将错误信息放到日志中
logComponentStackToMyService(info.componentStack);
}
render() {
const { f } = this.state
/*
* f
* true 表示子组件出现了意外错误
* false 表示子组件没有出现异常错误
*/
if ( f ) {
/* 回退UI OR 降级UI - 当子组件出错时,使用降级UI来代替崩溃的组件树 */
return <div> 您的网络异常,请检查后在尝试 </div>
} else {
return this.props.children //Home组件
}
}
}