生命周期的三个阶段:
-
初始化阶段:由ReactDOM.render()触发——初次渲染
- constructor() 构造器
- componentWillMount() 组件将要挂载
- render() 初始化渲染和状态更新之后调用,调1+n次
- componentDidMount() 常用 组件挂载完毕之后调用,只调一次 render的兄弟
一般在这个钩子中做一些初始化的事:开启定时器、发送网络请求、订阅消息
-
更新阶段:由组件内部this.setState()或父组件重新render触发
- shouldComponentUpdate() 控制组件更新的"阀门" 返回false时,页面就不会更新了,后面的生命周期也不会再执行
- componentWillUpdate() 组件将要更新的钩子
- render() 必须用的一个
-
componentDidUpdate() 组件更新完毕的钩子
-
卸载组件:由ReactDOM.unmountComponentAtNode()触发
- componentWillUnmount() 常用
一般在这个钩子中做一些收尾的事:关闭定时器、取消订阅消息
(以上是官方版本)
以下是我自己总结的,更详细点:
进入页面后生命周期的执行顺序
constructor 构造器
componengtWillMount 组件将要挂载
render 初始化渲染和状态更新之后调用,调1+n次
componentDidMount 组件挂载完毕之后调用,只调一次 render的兄弟
componentWillUnmount 组件将要卸载 可以用来清除定时器
以下是走setState之后的生命周期执行顺序
执行setState
shouldComponentUpdate 控制组件更新的"阀门" 返回false时,页面就不会更新了,后面的生命周期也不会再执行
componentWillUpdate 组件将要更新的钩子
render
componentDidUpdate 组件更新完毕的钩子
componentWillUnmount 组件将要卸载
以下是forceUpdate —— 不更改任何状态中的数据,强制更新的生命周期的执行顺序
执行forceUpdate
componentWillUpdate 组件将要更新的钩子
render
componentDidUpdate 组件更新完毕的钩子
父组件给子组件传值时生命周期的执行顺序
父组件的render
子组件的componentWillReceiveProps 但是第一次传值不会走这个生命周期,第二次传才会走
子组件的shouldComponentUpdata
子组件的componentWillUpdate
子组件的render
子组件的componentDidUpdate
其他生命周期
ReactDom.unmountComponentAtNode 卸载组件