2016-12-05 10 views
0

初期状態がストア状態と同じに設定されているコンポーネントがあります。また、コンポーネントは、ストアで発生するすべての変更に帰属します。特定のストアプロパティの変更をリッスンします

// Inital component's state is set to be equal to a Store state 
constructor(props) { 
    super(props); 
    this.state = EntityStore.getState(); 
    this.entitiesOnChange = this.entitiesOnChange.bind(this); 
} 

// Subscribe to any Store's change 
componentDidMount() { 
    EntityStore.listen(this.entitiesOnChange); 
} 

// Update the state with the new one 
entitiesOnChange(nextState) { 
    this.setState(nextState); 
} 

私の目標は、コンポーネントをストアの特定のプロパティにサブスクライブすることです。

entitiesOnChangeでチェックを試みましたが、this.stateは既にストアの状態(nextState)で最新であることがわかりました。

// Update the state with the new one only if a specefic `propery` is changed 
entitiesOnChange(nextState) { 
    // Here is the problem. `this.state` is already up to date. 
    if (this.state.property !== nextState.property) { 
     this.setState(nextState); 
    } 
} 

それでは、どのように、私は特定のストアのプロパティに私のコンポーネントを購読することができます両方の状態は、したがって、発生していない再レンダリング、同じであるので、また次のコード例では(私が試したものを)this.setState(nextState)は、呼び出されません?

+0

ドウはあなたがEntityStoreに状態を更新あなたのcoode内の他の場所を持っています変化する? –

+0

私は持っていますが、別のコンポーネント(上記の質問で使用されたコンポーネントではありません)にあります。 –

+0

その状態はすでに最新の状態になっている可能性はありますか?あなたのnextStateプロパティに本当にnextStateが含まれていますか? (現在のものではない) –

答えて

1

いいえ!私は深く問題を調査し、最終的に何が起きているのかを見つけました。この問題は、ストア内のデータを間違って設定することによって発生していました。それは突然変異していた(間違っている)。正しい(フラックス)方法は、新しいオブジェクトを作成しています。

私は、全体の問題を説明するためにJSFiddleを作成したが、ここではストアで間違った突然変異のハイライトですしました:

class Store { 
    constructor() { 
     this.bindActions(actions); 
     this.data = { 
      items: [], 
      isLoading: false 
     }; 
    } 

    set(items) { 
     this.data.isLoading = true; 

     // Simulate API call 
     setTimeout(() => { 
      this.data.items = items; 
      this.data.isLoading = false; 
      this.setState(this); 
     }, 2000); 

     this.setState(this); 
    } 
} 
関連する問題