React学习笔记9---组件的生命周期

组件的声明周期

理解

  • 组件从创建到死亡他会经历一些特定的阶段
  • 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()触发,初次渲染
    1. constructor
    2. componentWillMount
    3. render
    4. componentDidMount
  • 更新阶段:由组件内部的this.setState()和父组件重新render触发
    1. shouleComponentUpdate
    2. componentWillUpdate
    3. render
    4. componentDidUpdate
  • 卸载阶段:由ReactDom.unmountComponentAtNode()触发
    1. componentWillUnmount

生命周期流程图(新)

  • 挂载时
挂载时
|
constructor
|
getDerivedStateFromProps
|
render
|
componentDidMount
  • 更新时
newProps
|
getDerivedStateFromProps
|
shouldComponentUpdate
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
setState
|
getDerivedStateFromProps
|
shouldComponentUpdate
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
(forceUpdate)
|
render
|
getSnapShotBeforeUpdate
|
componentDidUpdate
  • 卸载时
ReactDom.unmountComponentAtNode
|
componentWillUnmount

生命周期的三个阶段(新)

  1. 初始化阶段,由ReactDom.render()触发,初次渲染
  • constructor()
  • getDerivedStateFromProps()
  • render()
  • componentDidMount
  1. 更新阶段,由组件内this.setState()和父组件重新render触发
  • getDerivedStateFromProps()
  • shodleComponentUpdate()
  • render()
  • getSnapShotBeforeUpdate()
  • componentDidUpdate
  1. 卸载阶段,由ReactDom.unmountComponentAtNode()触发
  • componentWillUnmount

重要的钩子

  1. render():初始化渲染和更新渲染调用
  2. componentDidMount:挂载完成时调用,开启监听,调用ajax请求
  3. componentWillUnmount:做一些收尾工作,比如清除定时器

即将废弃的钩子

  1. componentWillMount
  2. componentWillReceiveProps
  3. componentWillUpdate

现在使用会发出警告(16版本),下个大版本需要加上UNSAFE_前缀才能使用(17+),以后可能被彻底废弃掉,不建议使用

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容