2016-06-27 8 views
4

私が作成している変数はcomponentDidMount()です。componentDidUpdate()で利用可能にしたいと思います。何かご意見は?コードは次のようになります。componentDidMountで作成されたアクセス変数

class Example extends Component { 
    componentDidMount() { 
    const myVariable = 'this thing'; 
    } 

    componentDidUpdate() { 
    // I'd like my variable to be accessible here 
    console.log(myVariable); 
    } 

    render() {...} 
} 

答えて

8

コンポーネントに保存します。あなたが行う場合は、コンポーネントのライフサイクルを通じて再利用この変数に計画を立て、それを更新および/またはそれをレンダリングすることに注意してください - - それは最高に置かれ@Gosha Arinichは親切にそれを指摘したようにまた、

componentDidMount() { 
    this.myVariable = 'this thing'; 
} 

componentDidUpdate() { 
    // I'd like my variable to be accessible here 
    console.log(this.myVariable); 
} 

this.state)のstateである。

+1

オハイオ州の神私はあなたがそれを行うことができるか分からなかった...それは素晴らしいです!ありがとうございました! – jasonetco

+1

@jasonetco喜んでお手伝いします。 'this'の使い方を必ず読んでください。 Javascriptの難しい把握のコンセプトの1つです。関連性の高い質問と複数の回答が見つかりました[ここ](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –

+1

また、この値がコンポーネントのライフサイクル中に更新され、 'render'で使用されている場合は、それを状態にする方が良いでしょう。 –

関連する問題