• 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>
        );
      }
    }

     

  • 相关阅读:
    03 获取元素节点对象的方式
    02 window对象的常用方法
    01 BOM对象介绍
    10 for循环介绍和应用
    09 三元运算
    序列化pickle
    随机数random模块
    datetime模块时间运算
    time模块细讲
    时间处理模块
  • 原文地址:https://www.cnblogs.com/chenzxl/p/13225762.html
Copyright © 2020-2023  润新知