2016-07-03 6 views
0

私は定期的に更新されるコンポーネントを持っています。コンポーネントの更新時に内部状態を更新する必要があるこのコンポーネントの外部でユーティリティ関数を構築したいと思います。例えばReactコンポーネントがいつ更新されたかを確認する方法は?

:私はSample関数にUtility関数を渡すと、持っていた場合、私はこれを達成することができます知っている

class Sample extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { counter: 1 }; 
    } 
} 

class Utility { 
    constructor(componentInstance) { 
    this.internalNum = // computedInstance's internal counter state (how?) 
    // and when the component has updated, I'd like to change the internalNum (how?) 
    } 
} 

SampleUtility更新のリアクトライフサイクルメソッドに基づいていますが、私はしたくありませんそのような依存関係をSampleに導入する。

おそらく、ここでより良いデザインパターンがあるかもしれません...もしこれがうまくいけば、どのように動作しますか?

+0

「サンプル」の複数のインスタンスをレンダリングするとどうなりますか? –

答えて

0

おそらく、より良いデザインパターンは、基本的にあなたがSampleが新しい値でsetStateを呼び出すという事実にフックする必要があり、ここで

あります。このようなことは、Sample(コールバックまたはイベントとして)によって最もよく公開されます。

また、Sampleの状態をグローバルな場所に移動することもできます。 reduxを使用してください。

もっと

https://github.com/reactjs/redux

0

は、私はあなたが(それが岩のために)あなたはいつもReduxのを実装する必要がありますという理由だけでReduxのを実装する必要があります@basaratに同意します。とにかく、このシナリオでは静的なプロパティを使用して回避策をとることが可能です。

var _counter; 

class Sample extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { counter: 1 }; 
    _counter = 1; 
    } 

    updateCounter() { 
    var newCounter = this.state.counter + 1 

    this.setState({ counter: newCounter }); 
    _counter = newCounter; 
    } 

    static get counter() { return _counter; } 
} 

class Utility { 
    constructor(componentInstance) { 
    this.internalNum = Sample.counter; 
    } 
} 
関連する問題