前言:React中组件有生命周期,在16.3版本之后,我们把生命周期分为四个阶段:初始化、运行中、销毁和错误处理。值得注意的是,生命周期的钩子一定不要写成箭头函数!
一、15版本的钩子
getDefaultProps() (16版本已弃用)
getInitialState() (16版本已弃用)
componentWillMount()
render()
componentDidMount()
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
componentDidUpdate()
componentWillMount()
流程详见下图:
二、16版本的钩子
constructor() (较15版本新增)
componentWillMount() (17版本已弃用)
render()
componentDidMount()
componentWillReceiveProps() (17版本已弃用)
shouldComponentUpdate()
componentWillUpdate() (17版本已弃用)
componentDidUpdate()
componentWillUnMount()
componentDidCatch()
流程详见下图:
三、17版本(未来)的钩子
constructor()
static getDerivedStateFromProps() (较16版本新增)
render()
componentDidMount()
shouldComponentUpdate()
getSnapshotBeforeUpdate() (较16版本新增)
componentDidUpdate()
componentWillUnmount()
getDerivedStateFromError()
流程详见下图:
四、各生命周期钩子详解
1、constructor(props)
用来做属性的继承、状态的定义。(继承父组件外部传递来的属性,然后绑定在当前组件的props属性上)
官方建议不要在constructor引入任何具有副作用和订阅功能的代码,这些应当使用componentDidMount()
2、static getDerivedStateFromProps(nextProps, prevState)
在组件实例化后,和接受新的props后被调用
必须返回一个对象来更新状态,或者返回null表示新的props不需要任何state的更新
3、componentWillMount()
官方都建议使用componentDidMount()代替
4、render()
将JSX转换为虚拟对象模型
解析this.props和this.state
5、componentDidMount()
做数据修改、数据请求
可在这个钩子里初始化第三方的DOM库(只有到这里才能获取真实的DOM)
6、componentWillReceiveProps()
官方建议使用getDerivedStateFromProps函数代替
当组件挂载后,接收到新的props后会被调用
如果需要更新state来响应props的更改,则可以进行this.props和nextProps的比较,并在此钩子中使用this.setState
用来做监听
7、shouldComponentUpdate(nextProps, nextState)
决定组件是否更新渲染
默认返回true,即更新
返回false不会阻止子组件在state更改时重新渲染
是React性能优化的一种方案
8、componentWillUpdate()
组件更新前的准备工作,即生成虚拟DOM
不能在这里使用this.setState(),会造成栈溢出
9、getSnapshotBeforeUpdate()
在render()后的输出被渲染到DOM之前被调用
使组件能够在它们被潜在更改之前捕获当前值(如滚动位置)
返回的任何值都将作为参数传递给componentDidUpdate()
10、componentDidUpdate(prevProps, prevState, snapshot)
组件更新结束,可以做DOM操作
如果组件实现getSnapshotBeforeUpdate()生命周期,则它返回的值将作为第三个“快照”参数传递过去。否则,这个参数是undefined。
不能在这里使用this.setState(),会造成栈溢出
11、componentWillUnmount()
在此方法中执行任何必要的清理,例如使定时器无效,或清理在componentDidMount中创建的任何监听
内部销毁用ReactDOM.unmountComponentAtNode(),会销毁全部组件
外部销毁用开关来控制组件的创建与销毁
12、componentDidCatch(error, info)
可以在其子组件树中的任何位置捕获JavaScript错误
记录这些错误并显示回退UI,而不是崩溃的组件树
添加了context后会多一个钩子componentWillReact () {}