【一起来学React】- 16版本中生命周期的使用及建议

版权声明:本文为原创文章,转载请注明出处! https://blog.csdn.net/Fakin/article/details/85163005

在 V16 版本中引入了 Fiber 机制。这个机制一定程度上的影响了部分生命周期的调用,下面是个人使用的一点建议和心得!
文章首发:https://www.fakin.cn/2469.html

React渲染有两个阶段:reconciliation 和 commit 。前者过程是可以被打断的,后者则不能有任何的暂停,会一直更新界面直到完成。

Reconciliation 阶段

componentWillMount
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate

Commit 阶段

componentDidMount
omponentDidUpdate
componentWillUnmount

其实很好理解,看名字都知道will是即将,肯定能打断撒,举个例子,
componentWillReceiveProps,在使用的时候,你有没有遇到过,会执行两次或多次的bug?
所以v16中Reconciliation阶段建议除了shouldComponentUpdate以外其他的能不用就不要用。

V16生命周期使用建议
getDerivedStateFromProps 用于替换 componentWillReceiveProps ,该函数会在初始化和 update 时被调用,getSnapshotBeforeUpdate 用于替换 componentWillUpdate ,该函数会在 update 后 DOM 更新前被调用,用于读取最新的 DOM 数据。

class Fakin extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {}//替换componentWillReceiveProps 
  shouldComponentUpdate(nextProps, nextState) {}//是否更新
  componentDidMount() {}//组件被挂载
  getSnapshotBeforeUpdate(){}//替换componentWillUpdate 用于获得最新的 DOM 数据
  componentWillUnmount() {}//组件即将被销毁
  componentDidUpdate() {}//组件已经更新
  render() {}//渲染函数
   
}

需要注意的是getDerivedStateFromProps是静态方法。

猜你喜欢

转载自blog.csdn.net/Fakin/article/details/85163005
今日推荐