내가 보기 위해 쓰는 것/React.js

React.js - 이벤트 Error: Maximum update depth... 해결법

do1con 2019. 10. 29. 15:36

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

 

onClick 같은 이벤트에서 함수를 부르도록 쓰면 이 에러가 발생할 때가 있다.

그 해결법이다.

 

예를들어 이런 코드가 있다고 해보자

 

<button onClick={this._toggleState()}>메뉴</button>

 

이렇게 쓰면 당첨이다. 왜 Maximum update depth exceeded 가 뜨냐하면...

함수를 부른다 > render를 다시한다 > 또 함수를 부른다 > 반복

함수를 부른다? : {} 블럭안에 함수명+() 이렇게 썼기때문에 바로 호출의 의미가 된다.

 

리액트의 문법이 있다.

 

저 코드는 이렇게 쓰여야 한다.

 

<button onClick={this._toggleState}>메뉴</button>

 

매개변수가 필요하다면

 

<button onClick={() => this._toggleState(param)}>메뉴</button>

 

이렇게 써야 한다.