创建时(挂载阶段)
  • List item
  • 执行顺序:constructor()、render() 、componentDidMount()
钩子函数 触发时机 作用
constructor 创建时最先执行 初始化state、为事件处理程序绑定this
render 每次组件渲染都会触发 渲染UI,不能调用setState()
componentDidMount 组件挂在(完成DOM渲染)后 发送网络请求、DOM操作
  • 注意:setState() 的调用会触发render(),从而导致递归
更新时(更新阶段)
  • 执行时机:setState() 、forceUpdate() 、组件接收到新的props
  • 说明:以上三者任意一种变化,组件就会重新渲染
  • 执行顺序:render()、componentDidUpdate()
    钩子函数 触发时机 作用
    render 每次组件选人都会触发 渲染UI(与挂载阶段是同一个render)
    componentDidUpdate(prevProps) 组件更新(完成DOM渲染)后 发送网络请求、DOM操作、注意:如果要setState()必须放在if条件中,一般判断条件为,更新前后的props
卸载时(卸载阶段)
  • 说明:组件从页面中消失
    钩子函数 触发时机 作用
    componentWillUnmount 组件卸载 执行清理工作(比如清理定时器)
其他生命周期钩子
钩子函数 作用
shouldComponentUpdate 问题:有时候我们调用了setState() 但是没有改变里面state中的值或者props中的值没有发生变化都会导致UI渲染.解决方法:shouldComponentUpdate (nextProps, nextState), 中有两个参数,可以对比下次的state中的值和当前state中的值是否一样(nextState.number === this.state.number),来决定是否执行render钩子函数(return true 渲染、return false 不渲染)

react学习之路之生命周期

相关文章:

  • 2019-01-16
  • 2018-12-11
  • 2020-02-10
  • 2020-10-11
  • 2020-10-30
  • 2018-12-17
  • 2019-03-17
  • 2021-08-13
猜你喜欢
  • 2021-10-13
  • 2019-08-22
  • 2018-04-27
  • 2018-05-19
  • 2018-12-13
  • 2018-09-19
相关资源
相似解决方案