React生命周期

React生命周期

每个组件都有几个“生命周期方法”,您可以在此过程中的特定时间覆盖运行代码。前缀是will的方法在事情发生之前被调用,前缀的为did的方法在事情发生之后被调用。

  • Mounting 当创建组件的实例并将其插入到DOM中时,将调用这些方法:

    • constructor()
    • componentWillMount()
    • render()
    • componentDidMount()
  • Updating 更新可能是传入的参数或状态的改变引起的。当重新呈现组件时,将调用这些方法:

    • componentWillReceiveProps()
    • shouldComponentUpdate()
    • componentWillUpdate()
    • render()
    • componentDidUpdate()
  • Unmounting 当从DOM中删除组件时调用此方法:

    • componentWillUnmount()

我们将每个状态的方法归纳一下可能会方便我们的记忆

三个状态

  • Mounting:已插入真实 DOM
  • Updating:正在被重新渲染
  • Unmounting:已移出真实 DOM

五种方法

  • componentWillMount()
  • componentDidMount()
  • componentWillUpdate(object nextProps, object nextState)
  • componentDidUpdate(object prevProps, object prevState)
  • componentWillUnmount()

两种特殊状态

  • componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用
  • shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用

那么我们插入节点的时候,组件都做了什么呢?

  • constructor()
    • 构造函数,是用来初始化这个组件的,可以让组件的state根据传入的props的值不同而不同,如果你的组件是一个静态的,就可以不适用这个函数,下面是官网的例子
      constructor(props) {
          super(props);
          this.state = {
              color: props.initialColor
          };
      }
      
    • 注意这里面代码的第二行到第五行只能在第一次初始化的时候调用,千万别指望这种写法能够让你时时的更新你的组件
  • componentWillMount()
    • 当你的组件要�插入DOM时立刻被调用,render()将在他的后面被调用
    • 这个方法�不会同步更新state
    • 这是唯一一个在服务器上调用的方法,�应该使用constructor代替这个方法
  • render()
    • 这个是必须出现在你的组件中的方法,也是我们最经常用的方法
    • 在调用的时候应该检查this.statethis.props并且返回一个元素
    • 在这个组件中,不要更改组件的状态,不要与�浏览器发生交互
    • 如果你什么也不想让任何元素插入DOM,请reture false或return null
  • componentDidMount()
    • 尽可能多的将网络请求写在这里
    • 此方法中的设置状态将触发重新渲染。

接下来是更新节点

  • componentWillReceiveProps()
    • 在组件接收到新的props前被调用,
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()
    //未完待续
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容