React 的生命周期
constructor
构造函数中完成了 React 数据的初始化,它接受两个参数:props 和 context,当想在函数内部使用这两个参数时,需使用 super()传入这两个参数。
注意:只要使用了 constructor()就必须写 super(),否则会导致 this 指向错误。
componentWillUnmount
当组件已经初始化,但是还未渲染 DOM 时
componentWillUnmount
当组件实例被创建并插入 DOM 中
componentWillUnmount
当完成组件的卸载和数据的销毁时
一般再此处清除所有的定时器和事件监听
componentWillReceiveProps
当接受父组件改变后的 props 需要重新渲染组件时,接受一个参数 nextProps
shouldComponentUpdate
唯一用于控制组件重新渲染的生命周期,setState 以后,state 发生变化,组件会进入重新渲染的流程,在这里 return false 可以阻止组件的更新
可以用于性能优化(部分更新)
因为父组件的重新渲染会导致其所有子组件的重新渲染,这个时候其实我们是不需要所有子组件都跟着重新渲染的,因此需要在子组件的该生命周期中做判断
componentWillUpdate
shouldComponentUpdate 返回 true 以后,组件进入重新渲染的流程,进入 componentWillUpdate(也就是组件更新时),这里同样可以拿到 nextProps 和 nextState
componentDidUpdate
当组件组件更新完毕后,这里可以拿到 prevProps 和 prevState,即更新前的 props 和 state
render
render 函数会插入 jsx 生成的 dom 结构
getDerivedStateFromProps
当子组件接受到 props 时(代替 componentWillReceiveProps),接受两个参数 nextProps、prevState,可以根据 props 来更新 state,也可以触发一些回调,如动画或页面跳转等
getSnapshotBeforeUpdate
当子组件重新渲染时(代替 componentWillUpdate),接受两个参数 prevProps、prevState,保证和 componentDidUpdate 中读取到的 DOM 一致,此生命周期返回的任何值都将作为参数传递给 componentDidUpdate