2016-06-13 93 views
23

在反應組件中,最好是在構造函數()或componentWillMount()中設置初始狀態?在構造函數或componentWillMount中設置初始反應組件狀態?

export default class MyComponent extends React.Component{ 
    constructor(props){ 
    super(props); 
    this.setState({key: value}); 
    } 
} 

export default class MyComponent extends React.Component{ 
    componentWillMount(props){ 
    this.setState({key: value}); 
    } 
} 
+0

http://stackoverflow.com/questions/38137740/which-kinds-of-initialization-is-more-appropriate-in-constructor-vs-componentwil –

回答

34

在構造函數中使用ES6類時,但不使用setState API是最好的,而做像這樣:

export default class MyComponent extends React.Component{ 
    constructor(props){ 
    super(props); 
    this.state = { key: value }; 
    } 
} 

另外,如果你有班級屬性可用(巴伯階段1),那麼你可以做到以下幾點:

export default class MyComponent extends React.Component{ 
    state = { key: value }; 

    render() { 
    .... 
    } 
} 
+0

謝謝。使用setState API有什麼問題? – freedrull

+0

因爲我記得讀直接從不變異this.state: https://facebook.github.io/react/docs/component-api.html#setstate – freedrull

+6

對不起,要清楚,不要使用它時設置初始州。 :)其他地方是的。 – ctrlplusb

相關問題