• react-生命周期


    React生命周期图解

        一、旧版图解:

        二、新版图解:

    从图中,我们可以清楚知道React的生命周期分为三个部分:  实例化、存在期和销毁时。

    旧版生命周期如果要开启async rendering,在render函数之前的所有函数,都有可能被执行多次。

    旧版的React生命周期看图就可以啦,我们就不详细讲解了,下面我们来详细讲下,V16.4React的生命周期。

    由图中可以看到,React生命周期新引入了两个生命周期函数:getDerivedStateFromProps,    getSnapShotBeforeUpdate。

    getDerivedStateFromProps:

    getDerivedStateFromProps无论是Mounting还是Updating,也无论是因为什么引起的Updating,全部都会被调用。

    getSnapshotBeforeUpdate:

    getSnapshotBeforeUpdate()被调用于render之后,可以读取但无法使用DOM的时候。它使您的组件可以在可能更改之前从DOM捕获一些信息(例如滚动位置)。此生命周期返回的任何值都将作为参数传递给componentDidUpdate()。

    React官网中getSnapshotBeforeUpdate的例子:

    class ScrollingList extends React.Component {
      constructor(props) {
        super(props);
        this.listRef = React.createRef();
      }
    
      getSnapshotBeforeUpdate(prevProps, prevState) {
        // 我们是否要添加新的 items 到列表
        // 捕捉滚动位置,以便我们可以稍后调整滚动
        if (prevProps.list.length < this.props.list.length) {
          const list = this.listRef.current;
          return list.scrollHeight - list.scrollTop;
        }
        return null;
      }
    
      componentDidUpdate(prevProps, prevState, snapshot) {
        // 如果我们有snapshot值, 我们已经添加了 新的items
        // 调整滚动以至于这些新的items 不会将旧items推出视图
        // (这边的snapshot是 getSnapshotBeforeUpdate方法的返回值)
        if (snapshot !== null) {
          const list = this.listRef.current;
          list.scrollTop = list.scrollHeight - snapshot;
        }
      }
    
      render() {
        return (
          <div ref={this.listRef}>{/* ...contents... */}</div>
        );
      }
    }

     

  • 相关阅读:
    Spring AOP 随记
    Java设计模式系列 — 构造器模式
    【Java线程安全】 — 常用数据结构及原理(未完结)
    【最佳实践】好用的Quartz管理器类
    Timer和时间调度
    Java9之HashMap与ConcurrentHashMap
    记一次maven的包冲突经历
    hbase高可用集群部署(cdh)
    HBase 1.2.6 完全分布式集群安装部署详细过程
    hadoop-2.7.3完全分布式部署
  • 原文地址:https://www.cnblogs.com/chenzxl/p/13225762.html
Copyright © 2020-2023  润新知