React生命周期

React组件的生命周期(life cycle)根据广义定义描述,可以分为挂载,渲染和卸载这几个阶段,当渲染后的组件需要更新时,我们会重新渲染组件,这个阶段可能重复多次,直至卸载。
因此我们将React生命周期分为两类
- 当组件在挂载或卸载时
- 当组件接收新的数据时,即组件更新时

挂载或卸载过程

组件的挂载是最基本过程,这个过程主要做组件状态的初始化,我们推荐以下面的例子为模板写初始化组件

   import React, { Component, PropTypes } from 'react';
   class App extends Component {
      static propTypes = {
          // 定义props的类型
      };
      static defaultProps = {
          // 定义默认的props
      };
      constructor(props) {
          super(props);
          this.state = {
              // ...
          };
      }
      componentWillMount() {
          // 初始化只执行一次
          // 在render之前,不能通过refs拿节点
      }
      componentDidMount() {
          // 初始化只执行一次
          // 在render之后,可以通过refs拿到渲染后的节点,做一些我们想要的处理
      }
   }

我们看到propTypes和defaultProps被声明为静态属性,意味者从类外面也可以访问他们:App.propTypes和App.defaultProps。
如果在componentWillMount中执行setState方法,组件会更新state,但是只执行一次,所以初始化的state都可以放在这里。
如果在componentDidMount中执行setState方法,组件会重新渲染,但是这就相当于render之后再次render,这并不是一件好事,但是有些应用场景中,比如计算组件的位置或宽高时,就不得不让组件先渲染,更新必要的信息后再次渲染。
组件卸载非常简单,只有componentWillUnmount这一个卸载前状态:

   import React, { Component, PropTypes } from 'react';
   class App extends Component {
      componentWillUnmount(){
         //进行一些清理方法,如事件回收或者清除定时器
      }
      render(){
         return <div>...</div>;
      }
   }

数据更新过程

更新过程指的是父组件向下传递props或组件自身执行setState方法时一系列更新动作。这里只体现更新过程的生命周期

   import React, { Component, PropTypes } from 'react';
   class App extends Component {
      componentWillReceiveProps(nextProps) {
          // this.setState({})触发 shouldComponentUpdate
          // 如果没有在这里更新状态,那么不会重新渲染
      }
      shouldComponentUpdate(nextProps, nextState) {
          // return true
          // 接受新的state和props,如果不想重新渲染可以return false
      }
      componentWillUpdate(nextProps, nextState) {
          // ...
      }
      componentDidUpdate(prevProps, prevState) {
      }
      render(){
         return <div>...</div>;
      }

如果组件自身的state更新了,那么会依次执行shouldComponentUpdate,componentWillUpdate,render和componentDidUpdate

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值