에러 해결

[React]Cannot update a component (`Transaction`) while rendering a different component

눙엉 2021. 12. 10. 14:13

리액트로 프로젝트를 진행 중 동작에는 아무 문제가 없었지만 콘솔 창에는 Warning이 생긴 걸 발견했다.

Warning: Cannot update a component(`Transaction`) while rendering a different component (`OrderingCompanySelectModal`). To locate the bas setSTate() call inside `OrderingCompanySelectModal`, follow the stack trace as described in .... 

버전 16.13.0에서 추가되었다고 검색결과 알게 되었다.

 

다른 구성 요소에서 렌더링하는 동안 setState를 호출하면? 경고가 표시된다고 리액트 공식문서에 적혀있다. (번역기를 돌려도 이해를 하지 못했는데 코드를 수정해보며 이해를 했다)

 

해결 방법은 setState를 useEffect안에서 사용하면 에러가 해결된다고 한다.

 

아래는 에러가 발생한 코드이다.

  const handleSelectList = (e) => {
    if (state.radioState.first === true) {
      handleSelectBuyerType("pub");
    } else if (state.radioState.second === true) {
      handleSelectBuyerType("vendor");
    }
  };

state.radioState.first의 상태를 보고 handleSelectBuyerType의 함수를 실행시키는 로직이다.

여기서 handleSelectBuyerType는 props로 넘겨받은 setState를 동작시키는 핸들러였다.

 

다른 컴포넌트에서의 setState를 넘겨받아서 동작시킬땐 useEffect안에서 실행해야 한다고 Warning에서 친절히 알려주어서 맞게 수정하니 Warning이 사라졌다.

 

아래는 에러를 해결한 코드이다.

 useEffect(() => {
    if (state.radioState.first === true) {
      handleSelectBuyerType("pub");
    } else if (state.radioState.second === true) {
      handleSelectBuyerType("vendor");
    }
  }, [state.selectIndex]);