2016-06-22 73 views
2

當測試反應過來的生命週期,我發現了一個很奇怪,但困惑的問題:反應的生命週期:ReactDOM.render之前調用getDefaultProps

var TestLifeCycle = React.createClass({ 
    getInitialState : function(){ 
     console.log('2'); 
    }, 
    getDefaultProps : function(){ 
     console.log('1'); 
    }, 
    render : function(){ 
     return null; 
    } 
}); 
ReactDOM.render(<TestLifeCycle test="hello world!"/>, document.body); 

結果是:

1 
Warning: render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. 
2 

講究警告: getDefaultProps將在反應生命週期的最初階段進行調用。在我的理解,正確的控制檯日誌順序是:

warning 
1 
2 

,但在Chrome瀏覽器是:

1 
warning 
2 

是否getDefaultProps甚至比以前ReactDOM.render叫?

+0

是,getInitialState和getDefaultProps被稱爲前呈現。我的觀點是順序:注意警告位置。我認爲是[警告 - > 1 - > 2]。但控制檯是[1 - >警告 - > 2]。如何理解命令?順便說一下:document.body不會被反應提示。 – pingfengafei

回答

0

是的,getDefaultPropsrender之前被調用。 如文檔中所提及的,被創建並存儲靜態類時它被稱爲:

getDefaultProps的()的結果將被緩存,並用於確保 this.props.value將具有某個值它沒有被 父組件指定。

瞭解React的重要之處在於有三個不同的層。雖然大多數OOP只使用類和實例,但在反應中您有組件,元素實例。起初它往往有點混亂。

組件是「類」,即您想要創建的一般規範。實例是本規範的呈現版本,即DOM節點。在反應中,你很少直接操作實例,你最主要的工作是元素。

元素是一個「中間」層,用於定義特定組件元素在呈現前應如何呈現。這是您在編寫var elt = (<MyComponent prop1="bidule">)時所得到的結果。 元素是帶有一些屬性的普通JavaScript對象(道具,鍵,參考,&類型)。因此,在實際渲染之前,屬性已經存在了。

閱讀herehere瞭解更多關於組件,元素和實例的信息。

0

getDefaultPropsrender方法之前被調用。這是正確的行爲。如果我們去你的假設,認爲render首次調用

var TestLifeCycle = React.createClass({ 
    getInitialState : function(){ 
     console.log('2'); 
    }, 
    getDefaultProps : function(){ 
     console.log('1'); 
     return {className:'Test'} 
    }, 
    render : function(){ 
     return null; 
    } 
}); 
ReactDOM.render(<TestLifeCycle className={this.props.className} test="hello world!"/>, document.body); 

:您可以通過執行以下斷言這一點。那麼在此階段this.props.className將爲undefined

因此,反應調用getDefaultProps來查看是否有任何默認道具使用,然後在內部替換它們並正確渲染組件。

更多關於其他組件和它們的生命週期是指: https://facebook.github.io/react/docs/component-specs.html#getdefaultprops

+0

是的,getInitialState和getDefaultProps在渲染之前被調用。 – pingfengafei