1、组件生命周期的执行次数是什么样子的?
只执行一次: constructor、componentWillMount、componentDidMount
执行多次:render 、子组件的componentWillReceiveProps、componentWillUpdate、componentDidUpdate
有条件的执行:componentWillUnmount(页面离开,组件销毁时)
不执行的:根组件(ReactDOM.render在DOM上的组件)的componentWillReceiveProps(因为压根没有父组件给传递props)
2、组件的生命周期执行顺序是什么样子的?
假设组件嵌套关系是 App里有parent组件,parent组件有child组件。
如果不涉及到setState更新,第一次渲染的顺序如下:
App: constructor --> componentWillMount --> render -->
parent: constructor --> componentWillMount --> render -->
child: constructor --> componentWillMount --> render -->
componentDidMount (child) --> componentDidMount (parent) --> componentDidMount (App)
这时候触发App的setState事件
App: componentWillUpdate --> render -->
parent: componentWillReceiveProps --> componentWillUpdate --> render -->
child: componentWillReceiveProps --> componentWillUpdate --> render -->
componentDidUpdate (child) --> componentDidUpdate (parent) --> componentDidUpdate (App)
那如果是触发parent的setState呢
parent: componentWillUpdate --> render -->
child: componentWillReceiveProps --> componentWillUpdate --> render -->
componentDidUpdate (child) --> componentDidUpdate (parent)
那如果是只是触发了child组件自身的setState呢
child: componentWillUpdate --> render --> componentDidUpdate (child)
结论:
1、如图:完成前的顺序是从根部到子部,完成时时从子部到根部。(类似于事件机制)
2、每个组件的红线(包括初次和更新)生命周期时一股脑执行完毕以后再执行低一级别的红线生命周期。
3、第一级别的组件setState是不能触发其父组件的生命周期更新函数,只能触发更低一级别的生命周期更新函数。
3、很牛的shouldComponentUpdate
这个很牛的生命周期函数可以通过浅层对比有效减少页面重新加载的时间,在只更新一个子组件时可以阻止其他非相关组件的更新,从而提升效率;推荐用法如下:
import React, { PureComponent } from 'react'
class Example extends PureComponent {
render() {
// ...
}
}
使用过程中需要注意:见此篇文章