2016-07-13 18 views
2

ユーザーが入力バーを更新したときに、残りのAPIにフェッチを実行するつもりです。私が抱えている問題は、componentDidUpdateメソッドがjsonを減速機にディスパッチするアクションクリエータを呼び出し、状態を更新してcomponentDidUpdateを再度呼び出すことです。無限のサイクルを終了するためのアイデアやベストプラクティス?ありがとう!React Redux無限ループ

アクション作成者:

export const fetchFoods = (dispatch, searchText) => { 
    return fetch(`/nutrition/${searchText}`) 
    .then(res => res.json()) 
    .then(json => dispatch({type: 'RECEIVE_FOODS', json})) 
} 

リデューサー:

const foods = (state = [], action) => { 
    switch (action.type) { 
    case 'RECEIVE_FOODS': 
     return action.json 
    default: 
     return state 
    } 
} 

が反応コンテナ:

const FoodList = React.createClass({ 
    componentDidUpdate: function() { 
    fetchFoods(this.props.dispatch, this.props.searchText) 
    }, 
    componentWillMount: function() { 
    fetchFoods(this.props.dispatch, this.props.searchText) 
    }, 
    render: function() { 
    ... 
    } 
}) 

export default connect(
    (state) => { 
    return {searchText: state.searchText, foods: state.foods} 
    } 
)(FoodList) 
+0

更新が直ちに更新され、更新が強制されます。 –

+0

トリガするには、 '' connect''(https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options)で 'mapDispatchToProps'を使用したいと思うでしょう入力が変化したときの動作[こちら](http://redux.js.org/docs/basics/UsageWithReact.html)についても説明しています。 – robertklep

答えて

5

あなたはcomponentDidUpdateからfetchFoods機能を削除する必要があります。更新で関数を呼び出すと、あなたのように無限ループになります。

コンポーネントが最初にマウントされ、元のデータセットを取得したら、明示的に必要なときにのみアクションを呼び出すようにしてください。ユーザーがそれを変更した場合、別の関数がそれを変更するなどの変更を行います。

1

入力(または更新をトリガーしたいもの)にonChange()ハンドラーを付けると、入力が変更されるたびに明示的にディスパッチするその行動。

https://jsfiddle.net/julianljk/69z2wepo/49105/

機能:

handleChange: function (e) { 
    var myInput = e.target.value; 
    this.setState({ 
     value: myInput 
    }); 
    fetchFoods(this.props.dispatch, myInput) //sends it to the store, 
},   

レンダー:ライフサイクルメソッドでアクションの派遣を置く

render: function(){ 
    return( 
     <div> 
      <input type="text" value={this.state.value} onChange={this.handleChange}/> 
     </div> 
)}  

は、一般的行動のこの種を引き起こす可能性があります。