Vue、React 生命周期有哪些?页面数据获取放在哪个生命周期做比较好?

74 阅读1分钟

React 生命周期

  1. 挂载阶段(Mounting)

    • constructor()
    • static getDerivedStateFromProps()
    • render()
    • componentDidMount()
  2. 更新阶段(Updating)

    • static getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
    • getSnapshotBeforeUpdate()
    • componentDidUpdate()
  3. 卸载阶段(Unmounting)

    • componentWillUnmount()

Vue 生命周期

  1. 创建阶段

    • beforeCreate()
    • created()
  2. 挂载阶段

    • beforeMount()
    • mounted()
  3. 更新阶段

    • beforeUpdate()
    • updated()
  4. 销毁阶段

    • beforeDestroy()
    • destroyed()

页面数据获取最佳生命周期

  • React: componentDidMount 是获取数据的最佳时机,因为此时组件已经挂载,可以安全地进行 DOM 操作和异步请求。
  • Vue: mounted 是获取数据的最佳时机,因为此时组件已经被挂载,可以安全地进行 DOM 操作和异步请求。