簡體   English   中英

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調用保留在構造函數之外。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM