React生命周期

153 阅读1分钟
  • 初始化:组件类被实例化的时候
  • 挂载中:组件被插入DOM的时候
  • 更新中:新数据更新组件的时候
  • 卸载中:组件从DOM中移除的时候

image.png

1、设置属性和初始状态

  • defaultProps:默认属性
  • state:在构造函数中constructor()被初始化

2、挂载组件

挂载:将组件插入实际DOM的过程

  • componentWillMount():在组件挂载前设置状态都不会触发重新渲染,即使用setState()不会重新渲染;
  • componentDidMount():调用这个方法可以访问组件的refs

3、更新方法

  • componentWillReceiveProps (nextProps):接受父组件改变后的props需要重新渲染
  • shouldComponentUpdate(nextProps,nextState):如果返回false,则render()会被跳过直到下次状态发生改变;接下来的componentWillUpdatecomponentDidUpdate不会被调用;一般返回true;
  • componentWillUpdate (nextProps,nextState)
  • componentDidUpdate(prevProps,prevState)

4、卸载方法

卸载:DOM移除组件的过程(比如通过路由在不同页面跳转)

  • componentWillUnmount():一般在此过程清除定时器、切换设置。