React - 生命周期(二)
上一个写的是单个组件的生命周期,现在写一个,父子组件和兄弟组件之间生命周期的顺序
一、组件生命周期的执行次数是什么样子
-
只执行一次: constructor、componentWillMount、componentDidMount
-
执行多次:render 、子组件的componentWillReceiveProps、componentWillUpdate、componentDidUpdate
-
有条件的执行:componentWillUnmount(页面离开,组件销毁时)
-
不执行的:根组件(ReactDOM.render在DOM上的组件)的componentWillReceiveProps(因为压根没有父组件给传递props)
二、组件的生命周期执行顺序
假设组件嵌套关系是 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)
结论:
-
如图:完成前的顺序是从根部到子部,完成时时从子部到根部。(类似于事件机制)
-
每个组件的红线(包括初次和更新)生命周期时一股脑执行完毕以后再执行低一级别的红线生命周期
-
第一级别的组件setState是不能触发其父组件的生命周期更新函数,只能触发更低一级别的生命周期更新函数
React生命周期官方解析-
componentWillMount : 在渲染前调用,在客户端也在服务端。
-
componentDidMount : 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异步操作阻塞UI)。
-
componentWillReceiveProps : 在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。
-
shouldComponentUpdate : 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
可以在你确认不需要更新组件时使用。 -
componentWillUpdate : 在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。
-
componentDidUpdate : 在组件完成更新后立即调用。在初始化时不会被调用。
-
componentWillUnmount: 在组件从 DOM 中移除的时候立刻被调用。
-
参考链接: