2017-12-26 10 views
0

私は反応があります。私はURLのIDを切り替えるしたいと思います。タブ内のクリックごとに、異なる種類の商品リストが表示されます。私はcomponentDidUpdateメソッドから使​​用しました。問題は、次のタブをクリックすると、リストが前のリストから現在のリストに数回ジャンプしていることです。私は、componentDidUpdateのメソッドでsetStateを使用することで問題になる可能性があり、無限ループを引き起こす可能性があることを読んでいます。私は何か別のものを試しましたが、私は自分のコードで何を変えるべきなのか分かりません。 あなたはこのジャンプすることをどのように修正するか、何か考えてもらえますか?React app、componentDidUpdate - ジャンプリスト、無限ループ

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

答えて

0

これは私があなたの状況を処理する方法を次のとおりです。

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呼び出しをコンストラクタから外しておく必要があります。

+0

素晴らしい!それは最終的に動作します!どうもありがとうございました! :D –