我打算在用户更新输入栏时执行对我的其余 api 的提取。我遇到的问题是,componentDidUpdate 方法调用操作创建者,该操作创建者将 json 分派(dispatch)到 reducer ,进而更新状态并再次调用 componentDidUpdate。有什么想法或最佳实践可以结束无限循环吗?谢谢!
Action 创建者:
export const fetchFoods = (dispatch, searchText) => {
return fetch(`/nutrition/${searchText}`)
.then(res => res.json())
.then(json => dispatch({type: 'RECEIVE_FOODS', json}))
}
reducer :
const foods = (state = [], action) => {
switch (action.type) {
case 'RECEIVE_FOODS':
return action.json
default:
return state
}
}
react 容器:
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)
最佳答案
您应该从 componentDidUpdate
中删除 fetchFoods
函数。在更新时调用该函数将导致像您所描述的无限循环。
一旦组件首次安装并检索原始数据集,您应该仅在明确需要时调用该操作。如果用户更改它,另一个函数也会更改它,等等。
关于reactjs - React Redux 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38359583/