我有反应应用程序。我想在 url 中的 id 之间切换。选项卡中的每次点击都应显示不同类型的产品列表。我从方法 componentDidUpdate 中使用。问题是,当我单击下一个选项卡时,列表多次从上一个列表跳转到当前列表。我已经读到在方法 componentDidUpdate 中使用 setState 可能有问题,并且可能导致无限循环。我尝试了一些不同的事情来做,但我不知道应该在我的代码中更改什么。你有什么想法,如何解决这个跳跃的事情?
constructor(props) {
super(props);
this.state = {
food: []
};
var ingredient_type = this.props.params.id;
fetch('/food/type/'+ingredient_type)
.then(res => res.json())
.then(food=> this.setState({food}));
}
componentDidUpdate(){
var ingredient_type = this.props.params.id;
return fetch('/food/type/'+ingredient_type)
.then(res => res.json())
.then(food=> this.setState({food}));
}
render() {
let product_list = this.state.food.map((product, id) => <div className="row" key={id}>
<p className="cal_list col-lg-4 col-md-4 col-sm-4" >{product.name}</p>
<p className="cal_list1 col-lg-2 col-md-2 col-sm-2" >{product.calories}</p>
<p className="cal_list2 col-lg-2 col-md-2 col-sm-2" >{product.protein}</p>
<p className="cal_list3 col-lg-2 col-md-2 col-sm-2" >{product.fat}</p>
<p …Run Code Online (Sandbox Code Playgroud)