Skip to main content

生命周期

组件的生命周期

img

挂载阶段

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

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

更新阶段

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

卸载

  • componentWillUnmount()

错误处理

  • static getDerivedStateFromError()
  • componentDidCatch()

性能优化

  • render 里面尽量减少新建变量和 bind 函数
  • 定制 shouldComponentUpdate 函数 PureComponent
  • 不可变数据结构,Immutable.js Immer (是 mobx 的作者写的一个 immutable 库,核心实现是利用 ES6 的 proxy,几乎以最小的成本实现了 js 的不可变数据结构)