简体   繁体   English

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

[英]React app, componentDidUpdate - jumping list, infinite loop

I have react aplication. 我有反应的应用。 I would like to switch between id in url. 我想在URL中的ID之间切换。 Every click in the tab should show different kind of product list. 标签中的每次点击都应显示不同种类的产品列表。 I used from method componentDidUpdate. 我从方法componentDidUpdate使用。 The problem is, when I click in the next tab, the list is jumping from previous list to the present list several times. 问题是,当我单击下一个选项卡时,列表几次从前一个列表跳到当前列表。 I have read that it might be a problem with using setState in method componentDidUpdate and it can cause a infinite loop. 我已经读过,在componentDidUpdate方法中使用setState可能是一个问题,它可能导致无限循环。 I've tried something different things to do, but I have no idea, what I should change in my code. 我尝试了一些不同的事情来做,但是我不知道我应该在代码中进行哪些更改。 Could you have any idea, how to fix this jumping thing? 您有什么主意,如何解决这个跳跃的问题?

  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>)

This is how I would handle your situation: 这就是我如何处理您的情况:

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() {
  ...
}

The main difference is you just need to check if the id changed before fetching data. 主要区别在于您只需要在获取数据之前检查id是否已更改。 I also moved the initial fetch from the constructor to componentDidMount. 我还将初始获取从构造函数移至componentDidMount。 Generally want to keep side-effects and setState calls out of the constructor, even when async. 通常,即使在异步的情况下,也希望将副作用和setState调用保留在构造函数之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM