프론트엔드/ReactNative

[ReactNative] Class Component Error

SuzyL 2022. 11. 22. 13:30
반응형

리액트를 공부하지 않고 감으로 시작하시는 분들은 이런 에러를 봤을 수 있고

왜 일어나는지에 대해서 의문을 품을 수 있다. 

 

내가 겪은 에러였고 왜 그런지에 대해서 알고 싶었다. 

https://ko.reactjs.org/docs/hooks-overview.html#building-your-own-hooks

 

Class에서 구현하느냐 Function에서 구현하느냐 이 차이였다.

 

내가 맞이한 에러는 아래와 같다 

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

 

 

export class SampleClass extends ... {

  const {loading, error, data} = useQuery(SampleGQL);  render(){
    return (<>      ...
    </>)
  }
}
export const SampleClass = () => {
  const {loading, error, data} = useQuery(SampleGQL);
      return <>
        ...
      </>
}

위 두 코드중에서 에러를 발생하는 코드는 어떤 것일까?

위의 문서를 잘봤다면 Class로 구현한 스타일에 문제가 있다는 것을 알 것이다. 

 

 

오류가 나지않으려면 아래 코드와 같은 Function으로 구현하여 렌더링을 해야할 것이다.

 

function으로 구현할때는 아래와 같은것들을 고려해보자.

컴포넌트가 LifeCycle API도 사용하지 않고, state도 사용하지 않고, props만 전달해주는 뷰를 렌더링한다면, 함수형 컴포넌트를 사용할 수 있다.