반응형

리액트 게시판 만들기 진행 중 아래와 같은 에러가 발생하여 해결방법을 공유한다.

 

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.

 

일반적으로는 아래와 같은 케이스에서 오류가 발생했을 가능성이 높다.

 

<button onClick={this.handleButton()}></button>

 

이렇게 처리를 하면 버튼을 클릭했을 때뿐만 아니라 리 렌더링 시에도 메서드가 호출되기 때문에 무한루프가 발생한다.

 

해결 방법은 간단하다.

괄호를 삭제하면 된다.

 

<button onClick={this.handleButton}></button>

 

또는 아래와 같이 처리하면 된다.

 

<button onClick={() => {this.handleButton()}}></button>

 

매개변수가 필요하면 추가할 수도 있다.

 

<button onClick={() => {this.handleButton(arg1, arg2)}}></button>

 

반응형

 

위는 일반적인 케이스이고, 나처럼 특이한 케이스도 있다.

특이한 게 아니라 당연한 건데 모르는 것 일수도 있지만,, 나와 같은 행동을 하는 사람들을 위해 포스팅을 한다..

 

하고자 했던 것은 state가 변경됐을 때, 화면을 다시 렌더 하기 위한 기능 구현이었다.

그래서 아래와 같이 코드를 작성했다.

 

componentDidUpdate = (prevProps: any) => {
	this.detail();
};




detail = () => {
    Axios.get(`http://localhost:8000/detail?id=${this.props.boardId}`)
        .then((res) => {
            if (res.data.length > 0) {
                this.setState({
                    title: res.data[0].BOARD_TITLE,
                    content: res.data[0].BOARD_CONTENT,
                });
            }
        })
        .catch((e) => {
            console.error(e);
        });
};

 

데이터 불러오면 상태 변경이 일어나서 다시 세팅 > 세팅했으니 변경 > 다시 세팅 무한 루프가 발생했다.

componentDidUpdate을 쓰려면 바뀐 상태와 이전 상태를 비교해서 바뀌었을 때만 하던지.. 상태 관리를 잘해야 한다.

반응형