Vue一样,React整个组件生命周期包括从创建、初始化数据、编译模板、挂载Dom→渲染、更新→渲染、卸载等一系列过程

挂载、更新、卸载、捕错

挂载

1.constructor() 执行构造函数,初始化props、state
2.componentWillMount 发生在(render装配前)
3.render()
4.componentDidMount() 网络请求

更新

  1. shouldComponentUpdate(nextProps, nextState), 该声明周期要求返回boolean类型,返回true继续此次render,返回false则终止此次render

作用:
可在该生命周期函数中,对比nextState、nextProps与当前this.state、this.props,是否符合render的条件,从而避免不必要的render。 达到优化性能的目的。

  1. componentWillUpdate(nextProps, nextState), render前调用的最后一个方法,可以拿到nextProps,和nextState,任由处置,可以为渲染前做最后的操作

    注意:不能在该生命周期函数中执行setState方法,否则会导致无限循环调用更新

  2. render()

  3. componentDidUpdate(prevProps, prevState)

执行时机:组件更新结束后触发
在该方法中,可以根据前后的props和state的变化做相应的操作,如获取数据,修改DOM样式等

卸载

  1. componentWillUnMount()

此方法用于组件卸载前,清理一些注册是监听事件,或者取消订阅的网络请求等
一旦一个组件实例被卸载,其不会被再次挂载,而只可能是被重新创建

错误处理

  1. componentDidCatch(error, info) 错误处理