【学习笔记】React class生命周期整理

86 阅读1分钟

学而时习之,不亦说乎

摘要

常见React class生命周期整理

只列常见和比较重要的:

  • componentWillMount()或者UNSAFE_componentWillMount(),17+版本已废弃。
  • componentDidMount()
  • componentWillUnmount()
  • shouldComponentUpdate(),性能优化的关键。
  • render()

举个栗子

import { Component } from 'react'

interface Props {
  num: number
}

interface State {
  count: number
}

class Lifecycle extends Component {
  UNSAFE_componentWillMount(): void {
    /**
     * Called immediately before mounting occurs, and before Component#render. 
     * Avoid introducing any side-effects or subscriptions in this method.
     * This method will not stop working in React 17.
    */
    console.log('UNSAFE_componentWillMount()')
  }
  componentDidMount(): void {
    /**
     * Called immediately after a component is mounted.
     *  Setting state here will trigger re-rendering.
    */
    console.log('componentDidMount()')
  }
  componentWillUnmount(): void {
    /**
     * Called immediately before a component is destroyed. 
     * Perform any necessary cleanup in this method, such as cancelled network requests, or cleaning up any DOM elements created in componentDidMount.
    */
    console.log('componentWillUnmount()')
  }
  shouldComponentUpdate(nextProps: Readonly<Props>, nextState: Readonly<State>, nextContext: any): boolean {
    /**
     * Called to determine whether the change in props and state should trigger a re-render.
     * Component always returns true. PureComponent implements a shallow comparison on props and state and returns true if any props or states have changed.
     * If false is returned, Component#render, componentWillUpdate and componentDidUpdate will not be called.
    */
    console.log('shouldComponentUpdate:', nextProps, nextState, nextContext)
    return this.props.num !== nextProps.num
  }
  render() {
    console.log('render()')
    return (
      <div>Lifecycle</div>
    )
  }
}

export default Lifecycle

1. 初始化

输出顺序如下:

UNSAFE_componentWillMount()
render()
componentDidMount()

2. 更新

从父组件接收一个值,并通过点击按钮更新这个值。 输出顺序如下:

shouldComponentUpdate: {num: 2} null {}
render()

3. 卸载

在父组件增加num的值,使Lifecycle组件被卸载

{
    num < 3 && <Lifecycle num={num} />
}

输出内容:

componentWillUnmount()

总结

  1. componentWillMount()或者UNSAFE_componentWillMount(),不推荐再使用。
  2. componentDidMount(),会在组件初始化第一次渲染render()之后被调用。
  3. componentWillUnmount(),会在组件被卸载前调用,通常用来执行清理任务,如取消监听、清除计时器、关闭链接等。
  4. shouldComponentUpdate(),性能优化的关键,可以自主判断是否需要重新渲染组件,减少额外的性能损耗。return true重新渲染,反之则不重新渲染。