面试官:vue2、vue3、react类组件、react函数组件的渲染过程 ?

104 阅读2分钟

1. React类组件渲染过程:

  • 挂载阶段:

    • constructor(props): 初始化state,接收props,绑定方法
    • static getDerivedStateFromProps(props, state): 根据props更新state
    • render(): 调用React.createElement生成虚拟DOM
    • componentDidMount(): DOM挂载完成,可进行DOM操作
  • 更新阶段:

    • static getDerivedStateFromProps(props, state): props或state变化时调用
    • shouldComponentUpdate(nextProps, nextState): 决定是否重新渲染
    • render(): 调用React.createElement重新生成虚拟DOM
    • getSnapshotBeforeUpdate(prevProps, prevState): 获取DOM更新前的状态
    • componentDidUpdate(prevProps, prevState, snapshot): DOM更新完成
  • 卸载阶段:

    • componentWillUnmount(): 清理定时器、事件监听等

2. React函数组件渲染过程:

  • 首次渲染:

    • useState初始化state、接收props
    • 执行函数体
    • 调用React.createElement生成虚拟DOM
    • useEffect(空依赖数组)DOM挂载后执行
  • 更新阶段:

    • props或state变化触发重新渲染
    • 执行函数体
    • 调用React.createElement生成新的虚拟DOM
    • useEffect(有依赖数组)在依赖变化后执行
  • 卸载阶段:

    • useEffect返回的清理函数执行

3. Vue 2组件渲染过程:

  • 挂载阶段:

    • beforeCreate: 实例初始化
    • props => data => computed => methods => watch
    • created: 实例被创建,可发送网络请求,但DOM未挂载无法访问
    • beforeMount: 模板编译为render函数
    • render: 调用h函数生成虚拟DOM
    • mounted: DOM挂载完成可访问,可网络请求
  • 更新阶段:

    • beforeUpdate: 数据变化,DOM未更新
    • render: 调用h函数重新生成虚拟DOM
    • updated: DOM更新完成
  • 卸载阶段:

    • beforeDestroy: 实例销毁前
    • destroyed: 实例销毁后

4. Vue 3组件渲染过程:

  • 挂载阶段:

    • setup(): props => ref/reactive => computed => 函数方法 => watch/watchEffect
    • onBeforeMount: DOM挂载前
    • render: 调用createVNode函数生成虚拟DOM
    • onMounted: DOM挂载完成
  • 更新阶段:

    • onBeforeUpdate: 数据变化,DOM未更新
    • render: 重新生成虚拟DOM
    • onUpdated: DOM更新完成
  • 卸载阶段:

    • onBeforeUnmount: 实例卸载前
    • onUnmounted: 实例卸载后