React 应用程序,componentDidUpdate - 跳转列表,无限循环

React app, componentDidUpdate - jumping list, infinite loop

我有反应应用。我想在 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>)

我会这样处理你的情况:

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 调用保留在构造函数之外,即使在异步时也是如此。