React 的生命周期从广义上分为三个阶段:挂载、渲染、卸载
因此可以把 React 的生命周期分为两类:挂载卸载过程和更新过程。

1. 挂载卸载过程

constructor()

constructor()中完成了 React 数据的初始化,它接受两个参数:props 和 context,当想在函数内部使用这两个参数时,需使用 super()传入这两个参数。
注意:只要使用了 constructor()就必须写 super(),否则会导致 this 指向错误。

componentWillMount()

componentWillMount()一般用的比较少,它更多的是在服务端渲染时使用。它代表的过程是组件已经经历了 constructor()初始化数据后,但是还未渲染 DOM 时。

componentDidMount()

组件第一次渲染完成,此时 dom 节点已经生成,可以在这里调用 ajax 请求,返回数据 setState 后组件会重新渲染

componentWillUnmount ()

在此处完成组件的卸载和数据的销毁。

  1. clear 你在组建中所有的 setTimeout,setInterval
  2. 移除所有组建中的监听 removeEventListener
  3. 有时候我们会碰到这个 warning:
1
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
解决方法:

1
2
3
4
5
6
7
8
9
10
11
componentDidMount() {
this.isMount === true
axios.post().then((res) => {
this.isMount && this.setState({ // 增加条件ismount为true时
aaa:res
})
})
}
componentWillUnmount() {
this.isMount === false
}

2. 更新过程

2.1. componentWillReceiveProps (nextProps)

  1. 在接受父组件改变后的 props 需要重新渲染组件时用到的比较多
  2. 接受一个参数 nextProps
  3. 通过对比 nextProps 和 this.props,将 nextProps 的 state 为当前组件的 state,从而重新渲染组件
1
2
3
4
5
6
7
8
componentWillReceiveProps (nextProps) {
nextProps.openNotice !== this.props.openNotice&&this.setState({
openNotice:nextProps.openNotice
},() => {
console.log(this.state.openNotice:nextProps)
//将state更新为nextProps,在setState的第二个参数(回调)可以打 印出新的state
})
}

2.2.shouldComponentUpdate(nextProps,nextState)

  1. 主要用于性能优化(部分更新)
  2. 唯一用于控制组件重新渲染的生命周期,由于在 react 中,setState 以后,state 发生变化,组件会进入重新渲染的流程,在这里 return false 可以阻止组件的更新
  3. 因为 react 父组件的重新渲染会导致其所有子组件的重新渲染,这个时候其实我们是不需要所有子组件都跟着重新渲染的,因此需要在子组件的该生命周期中做判断

2.3.componentWillUpdate (nextProps,nextState)

shouldComponentUpdate 返回 true 以后,组件进入重新渲染的流程,进入 componentWillUpdate,这里同样可以拿到 nextProps 和 nextState。

2.4.componentDidUpdate(prevProps,prevState)

组件更新完毕后,react 只会在第一次初始化成功会进入 componentDidmount,之后每次重新渲染后都会进入这个生命周期,这里可以拿到 prevProps 和 prevState,即更新前的 props 和 state。

2.5.render()

render 函数会插入 jsx 生成的 dom 结构,react 会生成一份虚拟 dom 树,在每一次组件更新时,在此 react 会通过其 diff 算法比较更新前后的新旧 DOM 树,比较以后,找到最小的有差异的 DOM 节点,并重新渲染。。