나는 반응을 나타냈다. 나는 url에서 id 사이를 전환하고 싶다. 탭에서 클릭 할 때마다 다른 종류의 제품 목록이 표시됩니다. componentDidUpdate 메서드에서 사용했습니다. 문제는 다음 탭을 클릭하면 목록이 이전 목록에서 현재 목록으로 여러 번 건너 뛰고 있다는 것입니다. 나는 그것이 componentDidUpdate 메쏘드에서 setState를 사용할 때 문제가 될 수 있으며 무한 루프를 일으킬 수 있다는 것을 읽었다. 나는 다른 일을 시도했지만, 내 코드에서 무엇을 바꿔야할지 모른다. 이 점프 문제를 해결하는 방법에 대해 알고 싶습니까?React app, componentDidUpdate - 점프 목록, 무한 루프
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가 데이터를 가져 오는 전에 변경 한 경우 검사 할 필요가있다 :
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>)
좋아요! 마침내 작동합니다! 고마워요! :디 –