ReactJS入門3:組件的生命週期

來源:互聯網
上載者:User

標籤:bsp   判斷   world   upd   大括弧   rip   class   span   img   

    本文主要介紹組件的生命週期。

   組建的生命週期主要分為3個:Mounting、Updating、Unmounting.

1. Mounting:組件被載入到DOM

    在本階段,主要有三個方法:

1.1 getInitialState():object 設定初始狀態

1.2 componentWillMount() Mounting發生前調用

1.3 componentDidMount() Mounting發生後調用。該方法主要用於請求DOM節點的初始化。

 

2.Updating:DOM更新,組件被重新渲染

    在本階段,主要有四個方法:

2.1 componentWillReceiveProps(object nextProps) 當Mounted組件接受新的props時調用。該方法主要用於比較this.props和nextProps以使用this.setState()執行狀態轉換。

2.2 shouldComponentUpdate(object nextProps,object nextState):boolean 當組件判斷是否有保證DOM更新的改變時被調用。使用該方法作為比較this.props和nextProps、this.state和nextState的一種最佳化。如果React跳過更新,則返回false。

2.3 componentWillUpdate(object nextProps,object nextState) 更新前被調用。該方法內不能調用this.setState().

2.4 componentDidUpdate(object prevProps,object prevState) 更新完成後被調用。

 

3.Unmounting:組件被移除DOM

    在本階段,只有一個方法:

3.1 componentWillUnmount() 組件被移除和銷毀前調用。此處應Cleanup。

 

4.執行個體

var Hello = React.createClass({  getInitialState: function () {    return {      opacity: 1.0    };  },  componentDidMount: function () {    this.timer = setInterval(function () {      var opacity = this.state.opacity;      opacity -= .05;      if (opacity < 0.1) {        opacity = 1.0;      }      this.setState({        opacity: opacity      });    }.bind(this), 100);  },  render: function () {    return (      <div style={{opacity: this.state.opacity}}>        Hello {this.props.name}      </div>    );  }});ReactDOM.render(  <Hello name="world"/>,  document.getElementById(‘content‘));

     軟體實現的功能:在hello組件載入以後,通過 componentDidMount 方法設定一個定時器,每隔100毫秒,就重新設定組件的透明度,從而引發重新渲染。

     注意:組件的style屬性的設定方式也值得注意,不能寫成style="opacity:{this.state.opacity};",而要寫成style={{opacity: this.state.opacity}}。這是因為 React 組件樣式是一個對象,所以第一重大括弧表示這是 JavaScript 文法,第二重大括弧表示樣式對象。

    瀏覽器效果:“Hello world”逐漸淡化消失(迴圈)

 

ReactJS入門3:組件的生命週期

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.