组件的生命周期
组件的生命周期:组件从被创建到挂载到页面上使用,再到组件不用的时候卸载的过程
生命周期三阶段(执行时间、钩子函数执行顺序、钩子函数的作用)
-
创建时:
-
执行时间:组件创建时(页面加载时)
-
钩子函数执行顺序(constructor()、render()、componentDidMount())
-
constructor()
-
创建组件时,最先触发
-
作用:
-
初始化 state
-
为事件处理程序绑定 this
-
-
-
render()
-
每次组件渲染都会触发
-
作用:渲染 UI (注:不能调用 setState())
-
-
componentDidMount()
-
组件挂载完成后
-
作用:
-
发送网络请求
-
进行 DOM 操作
-
-
-
-
-
更新时:
-
执行时间:组件发生更新时
-
钩子函数执行顺序(render()、componentDidUpdate())
-
render()
-
每次组件渲染都会触发
-
作用:渲染 UI (注:不能调用 setState())
-
能触发组件更新的三种方法
-
组件接收到新的 Props
-
setState()
-
forceUpdate()
-
-
-
componentDidUpdate()
-
组件完成更新后
-
作用:
-
发送网络请求
-
进行 DOM操作
-
如果要进行 setState() 必须放在 if 条件中
-
-
-
-
-
卸载时:
-
执行时间:组件从页面中消失后
-
钩子函数(componentWillUNmount())
-
componentWillUnmount()
-
组件从页面中消失触发
-
作用:执行一些清理工作(定时器等)
-
-
-