react生命周期

一、生命周期

挂载

当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:

  • constructor() 如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
  • static getDerivedStateFromProps()
  • render() 渲染页面。
  • componentDidMount()会在组件挂载后(插入 DOM 树中)立即调用。这里添加网络请求和订阅。如果添加了订阅,请不要忘记在 componentWillUnmount()里取消订阅

注意:

下述生命周期方法即将过时,在新代码中应该避免使用它们:

  • UNSAFE_componentWillMount()

更新

当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:

  • static getDerivedStateFromProps()

  • shouldComponentUpdate()根据 shouldComponentUpdate() 的返回值,决定是否执行UNSAFE_componentWillUpdate()render()componentDidUpdate()

  • render()渲染页面。

  • getSnapshotBeforeUpdate()

  • componentDidUpdate()会在更新后会被立即调用。首次渲染不会执行此方法。当组件更新后,可以在此处对 DOM 进行操作。如果你对更新前后的 props 进行了比较,也可以选择在此处进行网络请求。(例如,当 props 未发生变化时,则不会执行网络请求)。

注意:

下述方法即将过时,在新代码中应该避免使用它们:

  • UNSAFE_componentWillUpdate()
  • UNSAFE_componentWillReceiveProps()

卸载

当组件从 DOM 中移除时会调用如下方法:

  • componentWillUnmount() 会在组件卸载及销毁之前直接调用。在此方法中执行必要的清理操作,例如,清除 timer,取消网络请求或清除在 componentDidMount()中创建的订阅等。componentWillUnmount()中不应调用 setState(),因为该组件将永远不会重新渲染。组件实例卸载后,将永远不会再挂载它。

错误处理

当渲染过程,生命周期,或子组件的构造函数中抛出错误时,会调用如下方法:

  • static getDerivedStateFromError()
  • componentDidCatch()

react生命周期_第1张图片
image.png

组件将要挂载时触发的函数:componentWillMount
组件挂载完成时触发的函数:componentDidMount
是否要更新数据时触发的函数:shouldComponentUpdate
将要更新数据时触发的函数:componentWillUpdate
数据更新完成时触发的函数:componentDidUpdate
组件将要销毁时触发的函数:componentWillUnmount
父组件中改变了props传值时触发的函数:componentWillReceiveProps

你可能感兴趣的:(react生命周期)