简述一下组件的生命周期

在进行组件化项目开发的时候都会存在一个组件的生命周期概念,像Vue、React、小程序等等,无一例外,而通常情况组件的生命周期主要分成三个阶段,包括:创建、更新以及销毁阶段。

Vue的生命周期钩子函数主要包括:

  1. beforeCreate(): 在实例初始化之后调用, data和methods都还没有初始化完成, 通过this不能访问
  2. created(): 此时data和methods都已初始化完成, 可以通过this去操作, 可以在此发ajax请求
  3. beforeMount(): 模板已经在内存中编译, 但还没有挂载到页面上, 不能通过ref找到对应的标签对象
  4. mounted(): 页面已经初始显示, 可以通过ref找到对应的标签, 也可以选择此时发ajax请求
  5. beforeUpdate(): 在数据更新之后, 界面更新前调用, 只能访问到原有的界面
  6. updated(): 在界面更新之后调用, 此时可以访问最新的界面
  7. beforeDestroy(): 实例销毁之前调用, 此时实例仍然可以正常工作
  8. destroyed(): Vue 实例销毁后调用, 实例已经无法正常工作了
  9. deactivated():组件失活, 但没有死亡
  10. activated(): 组件激活, 被复用
  11. errorCaptured(): 用于捕获子组件的错误,return false可以阻止错误向上冒泡(传递)

我们通常在created()/mounted()进行发送ajax请求,启动定时器等异步任务,而在beforeDestory()做收尾工作,如: 清除定时器操作。

不过需要注意的是mounted生命周期钩子中并不代表界面已经渲染成功,因为 mounted 不会保证所有的子组件也都一起被挂载。如果你希望等到整个视图都渲染完毕,可以在 mounted 内部使用 vm.$nextTick。

Vue的生命周期钩子函数又分为了:单个组件生命周期、父子组件的生命周期、带缓存的路由组件生命周期等不同的状态,在不同的状态下所拥有的生命周期内容是不相同的。

  • 单个组件生命周期
    初始化:

    • beforeCreate
    • created
    • beforeMount
    • mounted

    更新:

    • beforeUpdate
    • updated

    销毁:

    • beforeDestroy
    • destroyed
  • 父子组件的生命周期
    初始化:

    • beforeCreate

    • created

    • beforeMount

      • –child beforeCreate
      • –child created
      • –child beforeMount
      • –child mounted
    • mounted

    更新:

    • beforeUpdate

      • –child beforeUpdate

      • –child updated

    • updated

    销毁:

    • beforeDestroy
      • – child beforeDestroy
      • – child destroyed
    • destroyed
  • 带缓存的路由组件生命周期
    初始化:

    • mounted

      • –Child activated
    • activated

    路由离开

    • –Child deactivated
    • deactivated

    路由回来

    • –Child activated
    • activated
  • 捕获子组件错误的勾子
    子组件执行抛出错误

    • errorCaptured
阶段 Vue React 小程序应用 小程序页面
创建 beforeCreate constructor() onLaunch onLoad
created static getDerivedStateFromProps() onShow
beforeMount render() onReady
mounted componentDidMount()
更新 beforeUpdate static getDerivedStateFromProps() onShow onShow
updated shouldComponentUpdate() onHide onHide
deactivated render()
activated getSnapshotBeforeUpdate()
componentDidUpdate()
销毁 beforeDestroy componentWillUnmount() onUnload
destroyed
捕获错误 errorCaptured static getDerivedStateFromError() onError
componentDidCatch()

你可能感兴趣的:(前端,vue.js,react.js)