React生命周期

1、React 15 版本的生命周期

  • 挂载阶段html

    • constructor 构造函数react

    • componetWillMount 组件初始化渲染前调用web

    • render 组件渲染面试

    • componentDidMount 组件挂载到DOM后调用浏览器

  • 更新阶段网络

    • componentWillReceiveProps 组件将要接收新props前调用
    • shouldComponentUpdate 组件是否须要更新
    • componentWillUpdate 组件更新前调用
    • render 组件渲染
    • componentDidUpdate 组件更新后调用
  • 卸载阶段异步

    • componentWillUnmount 组件卸载前调用

2、16版本的生命周期

  • 挂载阶段函数

    • constructor构造函数,若是不初始化 state 或不进行方法绑定,则不须要为 React 组件实现构造函数。性能

    • static getDerivedStateFromProps(props, state) 会在调用 render 方法以前调用,而且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,若是返回 null 则不更新任何内容。code

    • render

    • componentDidMount 组件挂载到DOM后调用。在这里能够直接调用 setState()。它将触发额外渲染,但此渲染会发生在浏览器更新屏幕以前。从而保证了即便在render()两次调用的状况下,用户也不会看到中间状态。但它会致使性能问题,因此要谨慎使用。

  • 更新

    • static getDerivedStateFromProps
    • shouldComponentUpdate
    • render
    • getSnapShotBeforeUpdate 在最近一次渲染输出(提交到 DOM 节点)以前调用。它使组件能在发生更改以前从 DOM 捕获一些信息(例如,滚动位置)。它的任何返回值将做为参数传递给componentDidUpdate
    • componentDidUpdate 组件更新后调用,首次渲染不会执行此方法。在这里直接调用setState()时,必须将setState()包裹在一个条件语句里,不然会致使死循环。它还会致使额外的从新渲染,虽然用户不可见,但会影响组件性能。
  • 卸载

    • componentWillUnmount 这里不该调用setState(),由于组件不会从新渲染。
  • 错误处理

    • static getDerivedStateFromError 在后代组件抛出错误后被调用,将抛出的错误做为参数,并返回一个值以更新 state。
    • componentDidCatch

3、为何要移除componentWillMountcomponentWillReceivepPopscomponentWillUpdate

  • componentWillMount:异步渲染机制可能会致使单个组件实例能够屡次调用该方法。不少开发着目前会将事件绑定、异步请求等写在componentWillMount中,一旦异步渲染时componentWillMount被屡次调用,将会致使:
    • 进行重复的事件监听,没法正常取消重复的 Listener,更有可能致使内存泄漏
    • 发出重复的异步网络请求,致使 IO 资源被浪费
    • 在服务端渲染时,componentWillMount会被调用,可是会因忽略异步获取的数据致使 IO 资源被浪费
  • 大多数开发者使用componentWillUpdate的场景是配合componentDidUpdate,分别获取 rerender 先后的视图状态,进行必要的处理。但随着 suspense、time slicing、异步渲染等机制的到来,render 过程能够被分割成屡次完成,还能够被暂停甚至回溯,这致使**componentWillUpdatecomponentDidUpdate执行先后可能会间隔很长时间**,足够使用户进行交互操做更改当前组件的状态,这样可能会致使难以追踪的 bug。

参考:

  1. React 高频面试题梳理,看看面试怎么答?(上): mp.weixin.qq.com/s/3jmJgZFkt…
  2. 【React官网】React.Component: zh-hans.reactjs.org/docs/react-…
  3. 【IMWeb】谈谈新的 React 新的生命周期钩子: imweb.io/topic/5b8ca…
相关文章
相关标签/搜索