Javascript React应用程序,组件更新-跳转列表,无限循环

Javascript React应用程序,组件更新-跳转列表,无限循环,javascript,reactjs,components,infinite-loop,Javascript,Reactjs,Components,Infinite Loop,我已经申请了。我想在url中的id之间切换。选项卡中的每次单击都应显示不同类型的产品列表。我使用了from方法componentdiddupdate。问题是,当我单击下一个选项卡时,列表多次从上一个列表跳到当前列表。我已经读到,在方法componentDidUpdate中使用setState可能会有问题,它可能会导致无限循环。我试过做一些不同的事情,但我不知道我应该在代码中修改什么。 你知道怎么解决这个跳跃的问题吗 constructor(props) { super(props);

我已经申请了。我想在url中的id之间切换。选项卡中的每次单击都应显示不同类型的产品列表。我使用了from方法componentdiddupdate。问题是,当我单击下一个选项卡时,列表多次从上一个列表跳到当前列表。我已经读到,在方法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>)
构造函数(道具){
超级(道具);
此.state={
食物:[]
};
var component_type=this.props.params.id;
提取('/food/type/'+配料类型)
.then(res=>res.json())
.then(food=>this.setState({food}));
}
componentDidUpdate(){
var component_type=this.props.params.id;
返回获取('/food/type/'+配料类型)
.then(res=>res.json())
.then(food=>this.setState({food}));
}
render(){
让product_list=this.state.food.map((product,id)=>

{product.name}

{product.carries}

{product.protein}

{product.fat}

{product.carb}


以下是我如何处理您的情况:

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() {
  ...
}
主要区别在于,您只需要在获取数据之前检查id是否更改。我还将初始获取从构造函数移动到componentDidMount。通常希望将副作用和setState调用保留在构造函数之外,即使是异步的