2016-07-07 75 views
1
componentDidMount : function() 
{ 
    console.log(this);//1 
    console.log(this.state);//2 
} 

第1行顯示所有細節,不包括所有狀態變量,但第2行給出空對象。爲什麼?我如何訪問狀態變量或其他功能?「this」avaialable but「this.state」not available

+0

如果你沒有初始化任何狀態的組件。 'this.state'應該是一個空對象。 「其他功能」是什麼意思 – xiaofan2406

+0

瀏覽器的控制檯很懶,因此它會根據您的需求懶散地引用對象引用。爲確保'this'參考的實際內容 - 使用調試器並在發動機損壞時檢查它。 – zerkms

+0

@ xiaofan2406:我的意思是在課堂上定義的功能。 – Mihika

回答

1

這是預期的,因爲狀態需要在使用之前定義。與ES6類的常用方法是從構造函數中定義的初始狀態下,例如:

class MyCmp extends React.Component { 
    constructor() { 
     super(); // don't forget to call superclass constructor 
     this.state = {foo: 1}; 
    } 

    componentDidMount() { 
     console.log(this);//1 
     console.log(this.state);//2 
    } 
} 

如果使用建議等級的JavaScript(例如,如果你有0級或一些其他級數如在個人資料中巴貝爾配置),那麼你可以將它定義爲一個類屬性太:

class MyCmp extends React.Component { 
    state = { 
     foo: 1 
    }; 

    componentDidMount : function() { 
     console.log(this);//1 
     console.log(this.state);//2 
    } 
} 

如果你不使用ES6類,你會做這樣的事情:

var MyCmp = React.createClass({ 
    getInitialState: function() { 
     return { 
      foo: 1 
     } 
    }, 
    componentDidMount : function() { 
     console.log(this);//1 
     console.log(this.state);//2 
    } 
} 

我希望幫助。享受反應!

+2

如果你不使用ES6(我認爲?)你可以設置組件的getInitialState屬性:https://facebook.github.io/react/docs/component-specs.html – Fizz

+0

當然,我沒有立即明白。謝謝@Fizz,我更新了我的答案。 – Grgur

+0

我使用0.13版本..不是ES6 ..我用getInitialState更新所有組件。 – Mihika