组件生命周期

react-lifecycle React v16.4 组件生命周期,图片来自: http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

constructor(props)

  • 用于初始化 state
  • 唯一可以直接修改 state 的地方

getDerivedStateFromProps(props, state)

  • state 初始值通过 props 获取
  • 每次 render 前都会调用
  • 使用场景:表单控件获取默认值

render()

componentDidMount()

  • 只调用一次

componentWillUnmount()

  • 组件将被移除时调用
  • 使用场景:资源释放

getSnapshotBeforeUpdate(prevProps, prevState)

  • render 前调用,此时 state 已经更新
  • 使用场景:获取 render 之前的 DOM 状态

componentDidUpdate(prevProps, prevState, snapshot)

  • 每次 UI 更新后被调用

shouldComponentUpdate(nextProps, nextState)

  • 决定 Virtual DOM 是否要重绘
  • 使用场景:性能优化

参考