React 生命周期分为三种状态 1. 初始化 2.更新 3.销毁react
初始化es6
一、getDefaultProps()算法
设置默认的props,也能够用dufaultProps设置组件的默认属性 |
2.getInitialState()性能优化
在使用es6的class语法时是没有这个钩子函数的,能够直接在constructor中定义this.state。此时能够访问this.props |
3,componentWillMount()dom
组件初始化时只调用,之后组件更新不调用,整个生命周期只调用一次,此时能够修改state。 |
4,render()函数
react最重要的步骤,建立虚拟dom,进行diff算法,更新dom树都在此进行。此时就不能更改state了。 |
5,componentDidMount()性能
组件渲染以后调用,只调用一次 |
更新优化
6,componentWillReceiveProps(nextProps)this
组件初始化时不调用,组件接受新的props时调用。spa React 16.3 之后的版本加了两个生命周期。 |
7,shouldComponentUpdate(nextProps, nextState)
react性能优化很是重要的一环。组件接受新的state或者props时调用,咱们能够设置在此对比先后两个props和state是否相同,若是相同则返回false阻止更新,由于相同的属性状态必定会生成相同的dom树,这样就不须要创造新的dom树和旧的dom树进行diff算法对比,节省大量性能,尤为是在dom结构复杂的时候 |
八、componentWillUpdata(nextProps, nextState)
组件初始化时不调用,只有在组件将要更新时才调用,此时能够修改state,在 componentWillUpdate 的函数当中,此时能够更改 state, 好比 nextState.name = '你想要更改的值', render 的时候会用你更改的值。 这里面调用 this.setState() 要谨慎,不能每次在 componentWillUpdate 执行 this.setState(),不然会陷入死循环 |
9,render()
组件渲染 |
10,componentDidUpdate()
组件初始化时不调用,组件更新完成后调用,此时能够获取dom节点。 |
卸载
十一、componentWillUnmount()
组件将要卸载时调用,一些事件监听和定时器须要在此时清除。 |