【发布时间】:2016-07-13 18:52:20
【问题描述】:
当用户更新输入栏时,我打算执行对我的 rest api 的提取。我遇到的问题是 componentDidUpdate 方法调用将 json 分派到 reducer 的操作创建者,进而更新状态并再次调用 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)
【问题讨论】: