初始化
一、constructor
constructor参数接受两个参数props,context
能够获取到父组件传下来的的props,context,若是想在constructor构造函数内部(
注意是内部哦,在组件其余地方是能够直接接收的
)使用props或context,则须要传入,并传入super对象。
二、componentWillMount
1)组件刚经历constructor,初始完数据
2)还未进入render,组件还未渲染完成,dom还未渲染
componentWillMount 通常用的比较少,更多的是用在服务端渲染
ajax请求能写在willmount里吗?
1.虽然有些状况下并不会出错,可是若是ajax请求过来的数据是空,那么会影响页面的渲染,可能看到的就是空白。
2.不利于服务端渲染,在同构的状况下,生命周期会到componentwillmount,这样使用ajax就会出错
三、render
render函数会插入jsx生成的dom结构,react会生成一份虚拟dom树,在每一次组件更新时,在此react会经过其diff算法比较更新先后的新旧DOM树,比较之后,找到最小的有差别的DOM节点,并从新渲染
react16中 render函数容许返回一个数组,单个字符串等,不在只限制为一个顶级DOM节点,能够减小不少没必要要的div
四、componentDidMount
组件第一次渲染完成,此时dom节点已经生成,能够在这里调用ajax请求,返回数据setState后组件会从新渲染
更新
一、shouldComponentUpdate(nextProps,nextState)
惟一用于控制组件从新渲染的生命周期,因为在react中,setState之后,state发生变化,组件会进入从新渲染的流程,在这里return false能够阻止组件的更新
由于react父组件的从新渲染会致使其全部子组件的从新渲染,这个时候其实咱们是不须要全部子组件都跟着从新渲染的,所以须要在子组件的该生命周期中作判断
二、componentWillUpdate(nextProps,nextState)
shouldComponentUpdate返回true之后,组件进入从新渲染的流程,进入componentWillUpdate,这里一样能够拿到nextProps和nextState
三、componentDidUpdate(prevProps,prevState)
组件更新完毕后,react只会在第一次初始化成功会进入componentDidmount,以后每次从新渲染后都会进入这个生命周期,这里能够拿到prevProps和prevState,即更新前的props和state。
四、componentWillReceiveProps(nextProps)
componentWillReceiveProps在接受父组件改变后的props须要从新渲染组件时用到的比较多
它接受一个参数
nextProps
经过对比nextProps和this.props,将nextProps setState为当前组件的state,从而从新渲染组件
卸载
componentWillUnmount
componentWillUnmount也是会常常用到的一个生命周期,初学者可能用到的比较少,可是用好这个确实很重要的哦
1.clear你在组建中全部的setTimeout,setInterval
2.移除全部组建中的监听 removeEventListener
3.也许你会常常遇到这个warning:
Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.
This is a no-op. Please check the code for the undefined component.
是由于你在组建中的ajax请求返回中setState,而你组件销毁的时候,请求还未完成,所以会报warning,解决办法为
componentDidMount() { this.isMount === true axios.post().then((res) => { this.isMount && this.setState({
// 增长条件ismount为true时 aaa:res }) }) } componentWillUnmount() { this.isMount === false }