1. 程式人生 > >【07】react 之 生命周期

【07】react 之 生命周期

led render cti dup 一些事 復制代碼 pop 狀態機 document

閱讀目錄(Content)

  • 實例化
    • getDefaultProps
    • getInitialState
    • componentWillMount
    • render
    • componentDidMount
  • 存在期
    • componentWillReceiveProps
    • shouldComponentUpdate
    • componentWillUpdate
    • componentDidUpdate
  • 銷毀時
    • componentWillUnmount
  • 反模式

上篇博文使用React開發的一些註意要點對React開發的一些重點進行了簡單的羅列總結,雖然也提到了React生命周期,但只略微小結,在此單獨寫篇React生命周期的總結。

在組件的整個生命周期中,隨著該組件的props或者state發生改變,其DOM表現也會有相應的變化。一個組件就是一個狀態機,對於特定地輸入,它總返回一致的輸出。

一個React組件的生命周期分為三個部分:初始化(實例化)、存在期和銷毀時。下圖詳細列述了 React 組件在整個生命周期中所涉及的方法和行為:

技術分享

回到頂部(go to top)

實例化

當組件在客戶端被實例化,第一次被創建時,以下方法依次被調用:

1、getDefaultProps
2、getInitialState
3、componentWillMount
4、render
5、componentDidMount

當組件在服務端被實例化,首次被創建時,以下方法依次被調用:

1、getDefaultProps
2、getInitialState
3、componentWillMount
4、render

componentDidMount 不會在服務端被渲染的過程中調用。

getDefaultProps

對於每個組件實例來講,這個方法只會調用一次,該組件類的所有後續應用,getDefaultPops 將不會再被調用,其返回的對象可以用於設置默認的 props(properties的縮寫) 值。

技術分享
var MyTitle = React.createClass({
  getDefaultProps : function () {
    return {
      title : ‘Hello World‘
    };
  },

  render: function() {
     return <h1> {this.props.title} </h1>;
   }
});

ReactDOM.render(
  <MyTitle />,
  document.body
);
技術分享

React通過 propTypes 提供了一種驗證 props 的方式,propTypes 是一個配置對象,用於定義屬性類型:

技術分享
var MyTitle = React.createClass({
  propTypes: {
    title: React.PropTypes.string.isRequired,
  },

  render: function() {
     return <h1> {this.props.title} </h1>;
   }
});
技術分享

上面的Mytitle組件有一個title屬性。PropTypes 告訴 React,這個 title 屬性是必須的,而且它的值必須是字符串。現在,我們設置 title 屬性的值是一個數值。

技術分享
var data = 123;

ReactDOM.render(
  <MyTitle title={data} />,
  document.body
);
技術分享

這樣一來,title屬性就通不過驗證了。控制臺會顯示一行錯誤信息。

Warning: Failed propType: Invalid prop `title` of type `number` supplied to `MyTitle`, expected `string`.

常用的 PropTypes 如下:

技術分享 常用的PropTypes
getInitialState

對於組件的每個實例來說,這個方法的調用有且只有一次,用來初始化每個實例的 state,在這個方法裏,可以訪問組件的 props。每一個React組件都有自己的 state,其與 props 的區別在於 state只存在組件的內部,props 在所有實例中共享。

getInitialState 和 getDefaultPops 的調用是有區別的,getDefaultPops 是對於組件類來說只調用一次,後續該類的應用都不會被調用,而 getInitialState 是對於每個組件實例來講都會調用,並且只調一次。

技術分享
var LikeButton = React.createClass({
  getInitialState: function() {
    return {liked: false};
  },
  handleClick: function(event) {
    this.setState({liked: !this.state.liked});
  },
  render: function() {
    var text = this.state.liked ? ‘like‘ : ‘haven\‘t liked‘;
    return (
      <p onClick={this.handleClick}>
        You {text} this. Click to toggle.
      </p>
    );
  }
});

ReactDOM.render(
  <LikeButton />,
  document.getElementById(‘example‘)
);
技術分享

每次修改 state,都會重新渲染組件,實例化後通過 state 更新組件,會依次調用下列方法:

1、shouldComponentUpdate
2、componentWillUpdate
3、render
4、componentDidUpdate

但是不要直接修改 this.state,要通過 this.setState 方法來修改。

componentWillMount

該方法在首次渲染之前調用,也是再 render 方法調用之前修改 state 的最後一次機會。

render

該方法會創建一個虛擬DOM,用來表示組件的輸出。對於一個組件來講,render方法是唯一一個必需的方法。render方法需要滿足下面幾點:

  1. 只能通過 this.props 和 this.state 訪問數據(不能修改)
  2. 可以返回 null,false 或者任何React組件
  3. 只能出現一個頂級組件,不能返回一組元素
  4. 不能改變組件的狀態
  5. 不能修改DOM的輸出

render方法返回的結果並不是真正的DOM元素,而是一個虛擬的表現,類似於一個DOM tree的結構的對象。react之所以效率高,就是這個原因。

componentDidMount

該方法不會在服務端被渲染的過程中調用。該方法被調用時,已經渲染出真實的 DOM,可以再該方法中通過 this.getDOMNode()訪問到真實的 DOM(推薦使用 ReactDOM.findDOMNode())。

技術分享
var data = [..];
var comp = React.createClass({
    render: function(){
        return <imput .. />
    },
    componentDidMount: function(){
        $(this.getDOMNode()).autoComplete({
            src: data
        })
    }
})
技術分享

由於組件並不是真實的 DOM 節點,而是存在於內存之中的一種數據結構,叫做虛擬 DOM (virtual DOM)。只有當它插入文檔以後,才會變成真實的 DOM 。有時需要從組件獲取真實 DOM 的節點,這時就要用到 ref 屬性:

技術分享
var Area = React.createClass({
    render: function(){
        this.getDOMNode(); //render調用時,組件未掛載,這裏將報錯
        
        return <canvas ref=‘mainCanvas‘>
    },
    componentDidMount: function(){
        var canvas = this.refs.mainCanvas.getDOMNode();
        //這是有效的,可以訪問到 Canvas 節點
    }
})
技術分享

需要註意的是,由於 this.refs.[refName] 屬性獲取的是真實 DOM ,所以必須等到虛擬 DOM 插入文檔以後,才能使用這個屬性,否則會報錯。

回到頂部(go to top)

存在期

此時組件已經渲染好並且用戶可以與它進行交互,比如鼠標點擊,手指點按,或者其它的一些事件,導致應用狀態的改變,你將會看到下面的方法依次被調用

1、componentWillReceiveProps
2、shouldComponentUpdate
3、componentWillUpdate
4、render
5、componentDidUpdate

componentWillReceiveProps

組件的 props 屬性可以通過父組件來更改,這時,componentWillReceiveProps 將來被調用。可以在這個方法裏更新 state,以觸發 render 方法重新渲染組件。

技術分享
componentWillReceiveProps: function(nextProps){
    if(nextProps.checked !== undefined){  // 這裏checked是從父組件傳來的
        this.setState({
            checked: nextProps.checked
        })
    }
}
技術分享
shouldComponentUpdate

如果你確定組件的 props 或者 state 的改變不需要重新渲染,可以通過在這個方法裏通過返回 false 來阻止組件的重新渲染,返回 `false 則不會執行 render 以及後面的 componentWillUpdate,componentDidUpdate 方法。

該方法是非必須的,並且大多數情況下沒有在開發中使用。

shouldComponentUpdate: function(nextProps, nextState){
    return this.state.checked === nextState.checked;
    //return false 則不更新組件
}
componentWillUpdate

這個方法和 componentWillMount 類似,在組件接收到了新的 props 或者 state 即將進行重新渲染前,componentWillUpdate(object nextProps, object nextState) 會被調用,註意不要在此方面裏再去更新 props 或者 state。

componentDidUpdate

這個方法和 componentDidMount 類似,在組件重新被渲染之後,componentDidUpdate(object prevProps, object prevState) 會被調用。可以在這裏訪問並修改 DOM。

回到頂部(go to top)

銷毀時

componentWillUnmount

每當React使用完一個組件,這個組件必須從 DOM 中卸載後被銷毀,此時 componentWillUnmout 會被執行,完成所有的清理和銷毀工作,在 componentDidMount 中添加的任務都需要再該方法中撤銷,如創建的定時器或事件監聽器。

當再次裝載組件時,以下方法會被依次調用:

1、getInitialState
2、componentWillMount
3、render
4、componentDidMount

回到頂部(go to top)

反模式

在 getInitialState 方法中,嘗試通過 this.props 來創建 state 的做法是一種反模式。

技術分享
//反模式
getDefaultProps: function(){
    return {
        data: new Date()
    }
},
getInitialState: function(){
    return {
        day: this.props.date - new Date()
    }
},
render: function(){
    return <div>Day:{this.state.day}</div>
} 
技術分享

經過計算後的值不應該賦給 state,正確的模式應該是在渲染時計算這些值。這樣保證了計算後的值永遠不會與派生出它的 props 值不同步。

技術分享
//正確模式
getDefaultProps: function(){
    return {
        data: new Date()
    }
},
render: function(){
    var day = this.props.date - new Date();
    return <div>Day:{day}</div>
}
技術分享

如果只是簡單的初始化 state,那麽應用反模式是沒有問題的。

轉:http://www.cnblogs.com/MuYunyun/p/6629096.html

【07】react 之 生命周期