2017-02-17 24 views

回答

3

您使用ES6類,這意味着你需要使用一個構造函數初始化狀態:

class App extends Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      show: true 
     }; 
    } 

    // .. 
} 

參考:What is the difference between using constructor vs getInitialState in React/React Native?

+0

賓果。問題,但是:是否有任何理由不僅僅是向類本身添加state = {show:true},而不是引入構造函數?我已經這樣做了,它似乎工作正常。 –

+1

這應該很好,是的。但是你可能已經有了一個構造函數,例如將方法綁定到'this'之類。 –

+0

您可以在構造函數中初始化狀態,如答案中所示,也可以僅在類本身內使用靜態屬性'state',如之前的註釋中所述。 – nbkhope