2016-06-15 14 views
2

何かを初期化するメソッド(jQueryウィジェットなど)を使用している場合、initializeが一度だけ呼び出されるようにするにはどうすればよいですか?リフレッシュしたり、リフレッシュせずにそのページに移動したりするときに使用します。私の現在のアプローチは以下の通りです:componentDidUpdate()とcomponentDidMount()で一度だけ実行されることを確認する

// key used to make sure initialize() only runs in one of DidUpdate/DidMount 
let key = 0; 

Component = React.createClass({ 
    mixins: [ReactMeteorData], 
    hasKey() { 
    return key; 
    }, 
    getKey() { 
    key = 1; 
    }, 
    resetKey() { 
    key = 0; 
    }, 
    componentDidUpdate() { 
    if (!(this.hasKey())) { 
     initialize()(); 
     this.getKey(); 
    } 
    }, 
    componentDidMount() { 
    if (!(this.hasKey())) { 
     initialize()(); 
     this.getKey(); 
    } 
    }, 
    componentWillUnmount() { 
    this.resetKey(); 
    } 
}}) 
+1

あなたの質問を正しく理解していれば、 'componentDidMount'にイニシャライザを含めれば、必要なだけのものになるはずです。この関数は、コンポーネントがDOMにマウントされたときに一度だけ実行されます。ページを更新するかページに移動すると、このコンポーネントがマウントされ、イニシャライザ機能がトリガされます。 –

答えて

0

あなたはデフォルトで= falseでコンストラクタにプロパティを作成するかもしれないと思います。 didMount、didUpdate。そして、componentDidMountは一度だけ呼び出されるので、this.didMount = trueを置くことができます。 更新後、毎回componentDidUpdateが呼び出されますので、マストを確認してください:!this.didUpdate = (this.didUpdate = true); これらのプロパティだけをチェックしてください。

関連する問題