# React生命周期
# 一、v16.0前的生命周期
生命周期函数是指在某一个时刻组件会自动调用执行的函数。
- componentWillMount:在组件即将被挂载到页面的时刻执行(只会执行一次)。
- render:渲染。
- componentDidMount:在组件挂载到页面后的时刻执行(只会执行一次)。
- shouldComponentUpdate:在组件被更新之前执行(当state和props被改变的时候执行)。
- componentWillUpdate:在组件被更新之前执行,在
shouldComponentUpdate
之后执行,如果shouldComponentUpdate
返回false,则componentWillUpdate
以及后面的都不会执行。 - componentDidUpdate:在组件被更新之后执行。
- componentWillReceiveProps:一个组件要从父组件接收参数,只要父组件的
render
函数被重新执行了,这个方法就会执行(如果这个组件第一次存在于父组件中,不会执行,如果这个组件之前已经存在于父组件中,才会执行)。 - componentWillUnmount:当组件即将被从页面中移除的时候执行。
# 生命周期函数使用场景
- shouldComponentUpdate
父组件重新渲染的时候,子组件会默认也重新渲染,实际上子组件并没有发生变化。
// 子组件
render() {
console.log('child render'); // 父组件重新渲染的时候,子组件都会重新渲染,实际上子组件是没有变化的
const { name, test } = this.props
return (
<li>
<span>{test}-{name}</span>
<button onClick={this.handleClick}>删除</button>
</li>
)
}
2
3
4
5
6
7
8
9
10
11
优化措施如下:给子组件加一个shouldComponentUpdate
来优化避免无用的重新渲染。
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.name !== this.props.name) {
return true;
}
return false;
}
2
3
4
5
6
- componentDidMount
ajax异步请求放在 componentDidMount
周期函数里,因为这个函数只会执行一次,且不会有任何问题。
# 二、v16.4的生命周期
# 变更缘由
原来(React v16.0前)的生命周期在React v16推出的Fiber之后就不合适了,因为如果要开启async rendering,在render函数之前的所有函数,都有可能被执行多次。
原来(React v16.0前)的生命周期有哪些是在render前执行的呢?
- componentWillMount
- componentWillReceiveProps
- shouldComponentUpdate
- componentWillUpdate
除了shouldComponentUpdate
,其他在render函数之前的所有函数(componentWillMount
,componentWillReceiveProps
,componentWillUpdate
)都被getDerivedStateFromProps
替代。
也就是用一个静态函数getDerivedStateFromProps
来取代被deprecate的几个生命周期函数,就是强制开发者在render之前只做无副作用的操作,而且能做的操作局限在根据props和state决定新的state 。
React v16.0 刚推出的时候,是增加了一个componentDidCatch
生命周期函数,这只是一个增量式修改,完全不影响原有生命周期函数。但是,到了React v16.3 大改动来了,引入了两个新的生命周期函数。 getDerivedStateFromProps
和getSnapshotBeforeUpdate
# getDerivedStateFromProps
static getDerivedStateFromProps(props, state)
在组件创建时和更新时的render方法之前调用,它应该返回一个对象来更新状态,或者返回null来不更新任何内容。
由于组件的props改变而引发了state改变,这个state就是derived state
。
# getSnapshotBeforeUpdate
getSnapshotBeforeUpdate() 被调用于render之后,可以读取但无法使用DOM的时候。它使您的组件可以在可能更改之前从DOM捕获一些信息(例如滚动位置)。此生命周期返回的任何值都将作为参数传递给componentDidUpdate()。