2016-07-13 109 views
2

我必须执行当过用户更新输入酒吧取回我的REST API的意图。我遇到的问题是,componentDidUpdate方法调用行动的创建者,其调度JSON的减速,又将更新状态,并再次调用componentDidUpdate。任何想法或最佳实践来结束无限循环?谢谢!阵营终极版无限循环

行动者:

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

你可能想使用'mapDispatchToProps'与['connect'(https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options)来触发输入发生变化时的操作。还解释了[这里](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> 
)}  

把行动派遣的生命周期方法通常导致这种行为。