React筆記-組件生命週期

  React是一個UI庫,只需定義一次用戶界面,就可以將其用在多個地方,之後,當用的狀態(state)發生變化時,React將會自動做出反應,更新界面,其代碼偏向聲明式。需要關注的是其組件的概念,組件可以用於構建用戶界面,並通過任何適當的方式進行組合。一般來說,一個組件類由 extends Component創建,並且提供一個render方法以及其他可選的生命週期函數,組件相關的事件或方法來定義。

import React, { Component } from 'react';
import { render } from 'react-dom';

 class HelloMessage extends React.Component {
  render() {
    return <h1>Hello World!</h1>;
  }
}
 
const element = <HelloMessage name="Google"/>;
 
ReactDOM.render(
    element,
    document.getElementById('root')
);

     getInitialState :初始化this.state 的值,只在組件裝載之前調用一次。如果是使用ES6的語法,可以在構造函數中初始化狀態,如下:

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { count: props.initialCount };
  }
  render() {
    // ...
  }
}

        React 把組件看成是一個狀態機(State Machines)。通過與用戶的交互,實現不同狀態,然後渲染 UI,讓用戶界面和數據保持一致。React 裏,只需更新組件的 state,然後根據新的 state 重新渲染用戶界面.

      getDefaultProps:只在組件創建時調用一次並緩存返回的對象(即在React.createClass之後就會調用)。因爲這個方法在實例初始化之前調用,所以這個方法裏面不能依賴this獲取到這個組件的實例。在組件裝載之後,這個方法緩存的結果會用來保證訪問this.props的屬性時,當這個屬性沒有在父組件中傳入,也總是有值  如果是使用 ES6 語法,可以直接定義 defaultProps 這個類屬性來替代,這樣能更直觀的知道 default props 是預先定義好的對象值:

Counter.defaultProps ={initialCount:0};

render: 組裝生成這個組件的HTML結構

更新組件觸發:
 這些方法不在首次render組件的週期調用:

componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
 componentDidUpdate

 卸載組件觸發
 componentWillUnmount

生命週期圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章