组件的声明周期
理解
- 组件从创建到死亡他会经历一些特定的阶段
- React组件中包含一系列的钩子函数(声明周期回调函数),会在特定的时刻调用
- 我们在定义组件时,会在特定的声明周期回调函数中,做特定的工作
声明周期回调函数(旧)
- 挂载时
挂载时
|
constructor
|
componentWillMount
|
render
|
componentDidMount
|
componentWillUnmount
- setState
setState()
|
shouldComponentUpdate
|
componentWillUpdate
|
render
|
componentDidUpdate
|
componentWillUnmount
- forceUpdate
forceUpdate
|
componentWillUpdate
|
render
|
componentDidUpdate
|
componentWillUnmount
- 父组件render
父组件render
|
componentWillReceiveProps
|
shouldComponentUpdate
|
componentWillUpdate
|
render
|
componentDidUpdate
|
componentWillUnmount
生命周期的三个阶段(旧)
- 初始化阶段:由ReactDom.render()触发,初次渲染
- constructor
- componentWillMount
- render
- componentDidMount
- 更新阶段:由组件内部的this.setState()和父组件重新render触发
- shouleComponentUpdate
- componentWillUpdate
- render
- componentDidUpdate
- 卸载阶段:由ReactDom.unmountComponentAtNode()触发
- componentWillUnmount
生命周期流程图(新)
- 挂载时
挂载时
|
constructor
|
getDerivedStateFromProps
|
render
|
componentDidMount
- 更新时
newProps
|
getDerivedStateFromProps
|
shouldComponentUpdate
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
setState
|
getDerivedStateFromProps
|
shouldComponentUpdate
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
(forceUpdate)
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
- 卸载时
ReactDom.unmountComponentAtNode
|
componentWillUnmount
生命周期的三个阶段(新)
- 初始化阶段,由ReactDom.render()触发,初次渲染
- constructor()
- getDerivedStateFromProps()
- render()
- componentDidMount
- 更新阶段,由组件内this.setState()和父组件重新render触发
- getDerivedStateFromProps()
- shodleComponentUpdate()
- render()
- getSnapShotBeforeUpdate()
- componentDidUpdate
- 卸载阶段,由ReactDom.unmountComponentAtNode()触发
- componentWillUnmount
重要的钩子
- render():初始化渲染和更新渲染调用
- componentDidMount:挂载完成时调用,开启监听,调用ajax请求
- componentWillUnmount:做一些收尾工作,比如清除定时器
即将废弃的钩子
- componentWillMount
- componentWillReceiveProps
- componentWillUpdate
现在使用会发出警告(16版本),下个大版本需要加上UNSAFE_前缀才能使用(17+),以后可能被彻底废弃掉,不建议使用