2017-07-11 9 views
1

私のアプリでは、ステージに対応するステージとゲームがあります。私はcomponentDidMountでステージを取得し、次にcomponentWillReceivePropsでステージIDが減っているかどうかを確認してからステージのゲームをフェッチします。誰かが理由を説明することはできますか?あなたが言及したようにcomponentWillReceivePropsで呼び出されるアクションは、無限ループに入ります。

componentDidMount() { 
    this.props.fetchCurrentStage(); 
} 

componentWillReceiveProps(nextState) { 
    if (nextState.stageReducer && nextState.stageReducer.stageId) { 
    this.props.fetchGamesForStage(nextState.stageReducer.stageId);// Corresponding action is triggered infinite times.Why? 
    } 
} 
+1

'nextStage.stageReducer'と' nextState.stageReducer.stageId'の値を 'console.log'しようとしましたか?アクションが無限ループで呼び出されている場合は、状態を更新して再レンダリングをトリガするたびに、その条件が真でなければなりません。 –

+0

今、私はあなたのアプリケーションロジック全体を知らない。しかし、子がマウントされているときは、親 'fetchCurrentStage()'から関数を呼び出しています。親からそれを直接取得し、その結果を小道具として渡す方が良いでしょうか?これはあなたの問題を解決するものではありません。 – Chris

+0

また、 'nextState'は' nextProps'と呼ばれるべきでしょうか? – Chris

答えて

1

I check if there is stageId in reducer、私はあなたのmapStateToProps機能を書かれていることを、このようなものと仮定しています:

:あなたはこのような mapStateToProps何かを書く場合、それは素晴らしいことだ

const mapStateToProps = (state) => { 
    return { 
    stageReducer: state.stageReducer, 
    } 
} 

const mapStateToProps = (state) => { 
    return { 
    stageId: state.stageReducer ? state.stageReducer.stateId : undefined, 
    } 
} 

ちょうどパスからstateReducer全体ではないstateReducerとあなたが比較することができますcomponentWillReceivePropsの新しいstageId高齢stateIdこのような:初めてcomponentWillreceivePropsが呼び出されると

componentWillReceiveProps(nextProps) { 
    if (nextProps.stageId && this.props.stageId !== nextProps.stageId) { 
     this.props.fetchGamesForStage(nextState.stageId);// Corresponding action is triggered infinite times.Why? 
    } 
} 

this.props.stageId !== nextProps.stageIdはtrueに評価されます。したがって、対応するアクションがトリガーされます。

疑問:fetchGamesForStageの結果がサーバから取得されると、stageReducerの参照で変更されていると思います。そのため、componentWillReceivePropsが再び呼び出されます。これが正しい場合

が、その後、mapStateToProps

const mapStateToProps = (state) => { 
     return { 
     // other things from stageReducer 

     stageId: state.stageReducer ? state.stageReducer.stateId : undefined, 
     } 
    } 

からstageReducerから選択した項目を送信したり、あなたの構造を変更したくない場合は、これも役立つことがあります。

componentWillReceiveProps(newProps) { 
    const oldStageId = this.props.stageReducer ? this.props.stageReducer.stageId : undefined 
    const newStageId = newProps.stageReducer ? newProps.stageReducer.stageId : undefined 
    if (newStageId && oldStageId !== newStageId) { 
    this.props.fetchGamesForStage(newStageId);// Corresponding action is triggered infinite times.Why? 
    } 
} 

ホープ助けになる。

関連する問題