一、组件生命周期概述
1.初始化
在组件初始化阶段会执行
- constructor
- static getDerivedStateFromProps()
componentWillMount() / UNSAFE_componentWillMount()废弃- render()
- componentDidMount()
2.更新阶段
props或state的改变可能会引起组件的更新,组件重新渲染的过程中会调用以下方法:
componentWillReceiveProps() / UNSAFE_componentWillReceiveProps()废弃- static getDerivedStateFromProps()
- shouldComponentUpdate(nextProps,nextState)
componentWillUpdate() / UNSAFE_componentWillUpdate()废弃- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
3.卸载阶段
componentWillUnmount()
4.错误处理
componentDidCatch()
旧版的生命周期钩子函数
新版的生命周期函数
不常用的钩子函数
getDerivedStateFromProps()
getDerivedStateFromProps会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容- 不管原因是什么,都会在每次渲染前触发此方法
shouldComponentUpdate()
- 根据
shouldComponentUpdate()的返回值,判断 React 组件的输出是否受当前 state 或 props 更改的影响。默认行为是 state 每次发生变化组件都会重新渲染 - 当 props 或 state 发生变化时,
shouldComponentUpdate()会在渲染执行之前被调用。返回值默认为 true
getSnapshotBeforeUpdate()
getSnapshotBeforeUpdate()在最近一次渲染输出(提交到 DOM 节点)之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)。此生命周期的任何返回值将作为参数传递给componentDidUpdate()- 此用法并不常见,但它可能出现在 UI 处理中,如需要以特殊方式处理滚动位置的聊天线程等