生命周期函数:到某一时刻组件会自动调用执行的函数。
上图的分析:
(1):constructor
是第一个执行的,在里面执行的是初始化,例如state
跟props
的赋值,可以理解为一个周期函数,是es6
语发中自带的一个函数, 不写react
组件会自动创建一个空的
(2) : 初始化完以后 mounting
挂载
componentWillMount 组件第一次即将挂在到页面的时候执行
render 挂载
componentDidMount 组件第一次挂载完成后才会执行
( 3 ) : upDating
更新生命周期 分为:
state
更新出发的生命周期函数
props
更新触发的生命周期函数, 比state
多一个接受周期的函数
共同的周期
shouldComponentUpdate
在组件更新之前执行,返回一个布尔值,判断到底该不该更新改变的 state 或者props,也接受两个参数nextProps
,nextState
应用:
shouldComponentUpdate(nextProps,nextState){
if(nextProps.list.length !== this.props.list.length){
return true
}else{
return false
}
}
componentWillUpdate
在 shouldComponentUpdate
之后执行,是否执行取决于shouldComponentUpdate
返回是否是true
,接受两个参数nextProps
, nextState
props 单独的一个周期:
componentWillReceiveProps
在子组件接受到父组件传递的参数,第一次接受到props是不会执行的,只有第二次才会执行,子组件的这个周期就被执行了,有一个参数 props 是传递过来的prop的值
4: unmounting
卸载函数
注意:
新版本注意
componentWillMount
componentWillReceiveProps
componentWillUpdate
由于这个三个生命周期被滥用,在新版本17中会删除这个三个,但是有hack写法,参考文章
所有的周期函数如下:
static getDerivedStateFromProps(nextProps, prevState) {
4. Updating state based on props
7. Fetching external data when props change
}
constructor() {
1. Initializing state
}
componentWillMount() {
// 1. Initializing state 这个方法用的挺多,不过最新版就要去掉
// 2. Fetching external data
// 3. Adding event listeners (or subscriptions)
}
componentDidMount() {
componentDidMount 组件在挂载之后就会执行 只在第一次执行
2. Fetching external data
3. Adding event listeners (or subscriptions)
}
componentWillReceiveProps(props) { //可以接受props 方法
// 4. Updating state based on props
// 6. Side effects on props change
// 7. Fetching external data when props change
}
shouldComponentUpdate() {
}
componentWillUpdate(nextProps, nextState) {
// 5. Invoking external callbacks
// 8. Reading DOM properties before an update
}
render() {
}
getSnapshotBeforeUpdate(prevProps, prevState) {
8. Reading DOM properties before an update
}
componentDidUpdate(prevProps, prevState, snapshot) {
5. Invoking external callbacks
6. Side effects on props change
}
componentWillUnmount() {
}
其他: 父组件的render
函数执行的时候,里面的子组件的render
也会跟着发生变化,不管有没有传递数据,有时候会影响性能,因此可以采用生命周期来进行取消这没必要的浪费。