React组件的生命周期(理解)
React组件在网页中会经历创建、更新、删除三个过程。其生命周期也会历经三个过程:
- 装载过程(Mount)组件第一次在DOM中渲染。
- 更新过程(Update)组件重新渲染。
- 卸载过程(Unmount)组件在DOM中删除。
装载过程:
装载过程是组件第一次在DOM中渲染的过程,会依次调用如下函数:
- constructor
- getInitialState
- getDefaultProps
- componentWillMount
- render
- componentDidMount
constructor:
constructor函数是组件的构造函数,主要功能为:
1. 初始化state
2. 绑定函数的this环境(也可不进行绑定,函数使用ES6中的箭头函数即可绑定this到当前组件实例)
getInitialState && getDefaultProps:
1.getInitialState和getDefaultProps函数在ES6的React组件中不会用到,一个是设置初始状态,一个是设置默认属性。
componentWillMount:
componentWillMount也基本不会用到,componentWillMount发生在即将装载时,即使重新setState也已经迟了,不会引起重绘,所以componentWillMount的内容完全可以放在constructor中执行。
render:
render函数为纯函数,不可以在render函数中改变组件的props和state。组件中一定要有render函数,因为其他函数都有默认实现,而render函数没有。如果组件不需要渲染界面,则在render中返回null或者false即可。
componentDidMount:
当render函数返回的东西已经发生渲染后,会触发componentDidMount函数。该函数是经常使用的函数。
更新过程:
更新过程就是组件的props或者state改变时触发组件的更新。依次调用如下函数:
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
componentWillReceiveProps(nextProps):
只要父组件的render函数被调用,在其render函数中的子组件就会触发componentWillReceiveProps函数。
shouldComponentUpdate(nextProps, nextState):
规定什么时候需要重新渲染,用于提高React组件性能。
componentWillUpdate、componentDidUpdate:
类似于componentWillMount和componentDidMount,一个在render前,一个在render后。
卸载过程:
卸载过程只涉及一个函数:
componentWillUnmount
因为卸载组件后不需要再对组件有任何操作,所以只需要componentWillUnmount函数对组件删除之前进行一些操作即可。
整体流程图:
新的生命周期加入了static getDerivedStateFromProps (nextProps, prevState)和getSnapshotBeforeUpdate (prevProps, prevState)这两个钩子函数用来代替componentWillReceiveProps以及componentWillUpdate,也删除了componentWillMount。
static getDerivedStateFromProps (nextProps, prevState)可以直接return相应的state,以更新当前的state,如果没有状态更新,则return null.
getSnapshotBeforeUpdate (prevProps, prevState)发生在React更新Dom元素之前,获取一个快照,它返回的结果将作为componentDidUpdate(prevProps, prevState,snapShot)的第三个参数,可根据第三个参数的值在componentDidUpdate生命周期中进行状态更新。
同时,加入了错误捕获处理钩子函数componentDidCatch用来捕获错误。
参考文献: React官方教程