Pri*_*sia 2 javascript components infinite-loop reactjs
我有反应应用程序。我想在 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 className="cal_list4 col-lg-2 col-md-2 col-sm-2" >{product.carb}</p> </div>)
Run Code Online (Sandbox Code Playgroud)
这就是我将如何处理您的情况:
constructor(props) {
super(props);
this.state = {
food: []
};
}
componentDidMount() {
fetchFood(this.props.params.id)
}
componentDidUpdate(prevProps) {
if(this.props.params.id !== prevProps.params.id) {
fetchFood(this.props.params.id)
}
}
fetchFood(id) {
return fetch('/food/type/'+id)
.then(res => res.json())
.then(food=> this.setState({food}));
}
render() {
...
}
Run Code Online (Sandbox Code Playgroud)
主要区别在于您只需要在获取数据之前检查 id 是否更改。我还将初始提取从构造函数移到了 componentDidMount。通常希望将副作用和 setState 调用保留在构造函数之外,即使在异步时也是如此。
| 归档时间: |
|
| 查看次数: |
660 次 |
| 最近记录: |