React——生命周期

2016-05-30  本文已影响122人  天外来人

三大阶段:
创建期:在组件创建的时候出现
存在期:在组件发生属性或者状态数据改变的时候
销毁期:组件从页面中移除的时候

创建期

1 getDefaultProps 设置默认属性
2 getInitialState 设置初始状态
3 componentWillMount 组件将要被构建(虚拟dom)
4 render 组件渲染输出虚拟dom
5 componentDidMount 组件已经构建完成(真是dom)

var Div = React.createClass({
  getDefaultProps: function() {
    console.log('我是:getDefaultProps');
    return {};
  },
  getInitialState: function(){
    console.log('我是:getInitialState');
    return {};
  },
  componentWillMount: function() {
    console.log('我是:componentWillMount');
  },
  render: function) {
    console.log('我是:render');
    return (
      <div>我叫好奇心日报</div>
    );
  },
  componentDidMount: function() {
    console.log('我是:componentDidMount');
    console.log(ReactDOM.findDOMNode(this));
  }
});

先来看下执行顺序:

Paste_Image.png
执行顺序是自上而下依次执行
需要注意点:

存在期

1 componentWillReceiveProps 组件即将接收新的属性
2 shouldComponentUpdate 组件是否应该更新
3 componentWillUpdate 组件即将更新
4 render 渲染输出虚拟DOM
5 componentDidUpdate 组件已经更新完毕

var Div = React.createClass({
 componentWillReceiveProps: function(nextProps) {
    console.log('我是:componentWillReceiveProps');
  },
 shouldComponentUpdate: function(nextProps, nextState){
    //第一个参数表示新的属性
    //第二个参数表示新的状态
    console.log('我是:shouldComponentUpdate');
    return true;
  },
 componentWillUpdate: function(nextProps, nextState) {
    //第一个参数表示新的属性
    //第二个参数表示新的状态
    console.log('我是:componentWillUpdate');
  },
  render: function) {
    console.log('我是:render');
    return (
      <div>我叫好奇心日报</div>
    );
  },
  componentDidUpdate: function(nextProps, nextState) {
    //第一个参数表示上一个属性
    //第二个参数表示上一个状态
    console.log('我是:componentDidUpdate');
    console.log(ReactDOM.findDOMNode(this));
  }
});

需要注意点:

销毁期

componentWillUnmount: 在删除组件之前进行清理操作,比如计时器和事件监听。

上一篇 下一篇

猜你喜欢

热点阅读