react的最新生命周期

文章借鉴地址:这篇文章

缘由

react打算在17版本退出Async/Rendering,提出一种可能被打断的声明周期,而可以被打断的阶段正是实际dom挂载之前的虚拟dom构建阶段,也就是要被去掉的三个生命周期。

旧的:

componentWillMount,componentWillReceiveProps,componentWillUpdate

新的:

static getDerivedStateFromProps,getSnapshotBeforeUpdate

生命周期一旦被打断,恢复时会再跑一次之前的生命周期,componentWillMount,componentWillReceiveProps,componentWillUpdate不能保证只在挂载/拿到props/状态变化的时候刷新了一次,所以会被标记为不安全。

两个新生命周期

static getDerivedStateFromProps

触发时间:在组件构建之后,虚拟dom之后,实际dom挂载之前。以及每次获取新的props之后。

每次接受新的props都会返回一个对象作为新的state,如果null则不需要更新state。

配合componentDidUpdate,能够componentWillReceiveProps的所有用法。

componentDidUpdate 在组件完成更新后立即调用。在初始化时不会被调用

class Example extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    //do somthing 
  }
}

getSnapshotBeforeUpdate

触发时间:update发生的时候,在render之后,在组件dom渲染之前。

返回一个值,作为componentDidUpdate的第三个参数。

配合componentDidUpdate,可以覆盖componentWillUpdate的所有用法。

componentWillUpdate在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。

class Example extends React.Component {
  getSnapshotBeforeUpdate(prevProps, prevState) {
    //do somthing
  }
}

用法:

请求数据--fetch data

在componentDidMount请求异步加载的数据。

在componentWillMount请求的数据在render就能拿到,但其实render在willMount之后几乎是马上被调用的,根本等不到数据的回来,同样需要render一次加载中的空状态。

根据props更新state--updating state based on props

用getDerivedStateFromProps(nextProps,prevState),将传入的props更新到state上。

来代替componentWillReceiveProps(nextProps, nextState),willReceiveProps经常被误用,导致了一些问题,因此该方法将不被推荐使用。

旧版本的生命周期图,红色框线的是将会被移除的。

最后附上个人公众号,定期发一些视频教程~

需要什么教程留言即可~

猜你喜欢

转载自blog.csdn.net/qq_33589252/article/details/84029718
今日推荐