React生命周期, setState、props改变触发的钩子函数

一. setState改变会触发的生命周期钩子

  1. shouldComponentUpdate
  2. componentWillUpdate
  3. render
  4. componentDidUpdate

二. props改变会触发的生命周期

  1. componentWillReveiceProps
  2. shouldComponentUpdate
  3. componentWillUpdate
  4. render
  5. componentDidUpdate

三. React生命周期

React生命周期, setState、props改变触发的钩子函数_第1张图片
image.png

1:挂载卸载过程

1.1.constructor()

此方法中完成了数据的初始化,它接受两个参数props,context, 如果再函数中想使用这两个参数必须使用super(), 用来将this指向父组件, 否则会报错

1.2.componentWillMount()

componentWillMount() 一般情况写用到的比较少。constructor()已经初始化了数据但是DOM还未渲染

1.3.componentDidMount()

组件第一次渲染完成,此时DOM节点已经生成。一般在此方法中进行ajax请求,返回数据setState重新渲染

1.4.componentWillUnmount()

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

2:更新过程

2.1 componentWillReveiceProps(nextProps)

在接受父组件改变后的props需要重新渲染组件时用到的比较多。将nextProps的state为当前组件的state,从而渲染组件

2.2 shouldComponentUpdate(nextProps, nextState)

可用于性能优化(部分更新)在setState后, state发生变化, return false时可以阻止组件更新。
父组件的重新渲染会导致子组件也重新渲染, 这个时候如果我们不需要所有子组件都跟着重新渲染, 可以在子组件的该生命周期中做判断

2.3 componentWillUpdate(nextProps, nextState)

shouldComponentUpdate返回true,则进入改流程

2.4 componentDidUpdate(preProps, preState)

组件的每次更新都会执行此钩子函数, 通过参数可以拿到更新前的props和state

2.5 render()

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

你可能感兴趣的:(React生命周期, setState、props改变触发的钩子函数)