본문 바로가기

REACT/해결방안

[React]ComponentDidUpdate() 내에서 Setstate 를 사용하는 방법(무한루프 방지)

참조 : https://stackoverflow.com/questions/37937250/componentdidupdate-setstate-reactjs-infinite-loop

 

ComponentDidUpdate SetState ReactJS Infinite loop

Even though there are many questions with the same subject line, I could not get an answer for my problem. Problem I have a select dropdown. On click of which, I call an Api which fetches ...

stackoverflow.com

 

Setstate 를 사용할 때, 리렌더링됨과 더불어 ComponentDidUpdate 함수도 호출하게 된다.

 

그래서 조건문을 사용하여 그다음 호출에는 Setstate가 사용되지 않게 한다.

 

componentDidUpdate() {

 const a = 0;

 if(this.state.a !== 0) {

  this.setState({ a : 0 })

 }

}