2016-05-24 7 views
0

私のReact-Railsアプリケーションでは、なぜcomponentWillMountのコンソールに状態を記録できないのか混乱していますが、componentDidMountではこれを行うことができます。以下はcomponentWillMountではコンソールに状態を記録できませんが、componentDidMountで状態を記録できないのはなぜですか?

私のコードです:

componentWillMount() { 
    this.setState({ records: this.props.data }); 
    console.log(this.state.records); // throws TypeError: Cannot read property 'records' of null 
} 
componentDidMount() { 
    console.log(this.state.records); // returns records array 
} 

任意のアイデア?ありがとう! the docsから

答えて

0

setState()すぐthis.stateを変異させたが 保留の状態遷移を作成しません。この メソッドを呼び出した後にthis.stateにアクセスすると、既存の値が返される可能性があります。

換言すれば、this.statecomponentWillMount時に定義されていないとsetState()を使用すると、それが定義されることはありません。 componentDidMountに達すると、設定した値でthis.stateが定義されます。

+0

ありがとうございました! –

関連する問題