Trouble Shooting - RN navigation 사용 시 타입을 지정하지 않으면 나는 에러

제이제이리·2023년 12월 4일

💥TroubleShooting💥

목록 보기
1/2

에러 상황

맨 처음 react-navigaton 설치 후, 타입 지정하지 않으면 아래 같은 에러가 난다.

Type '({ navigation }: MainScreenProps) => Element' is not assignable to type 'ScreenComponentType<ParamListBase, "Main"> | undefined'.
  Type '({ navigation }: MainScreenProps) => Element' is not assignable to type 'FunctionComponent<{}>'.
    Types of parameters '__0' and 'props' are incompatible.
      Type '{}' is missing the following properties from type 'MainScreenProps': navigation, route
//타입이 없다고 한다!

해결 방법

이를 해결하기 위해, 타입을 미리 지정해 줘야하는데,

  1. 모든 컴포넌트의 navigation 시, route(페이지 이동시 전달할 인자나 함수 등)에 대한 타입과
  2. 페이지 내 props로, 위의 타입을 지정해 둔 리스트와 해당하는 페이지의 이름을 전달하는 타입
import {NativeStackScreenProps} from '@react-navigation/native-stack';

// route를 통해 전달받을 인자가 없다?! 그럼 undefined, 혹은 route에서 받을 인자의 타입을 쓰는 것임
export type RootStackParamList = {
  Main: undefined;
  Plogging: {
    shouldOpenModal?: boolean;
  };
  Camera: undefined;
};

// 여기는 MainPage를 위한 Props로 위에 있는 RootStackParamList 중에서
// 해당하는 페이지인 'Main'를 지정해주어 메인 화면에 특화된 속성을 전달함.
export type MainScreenProps = NativeStackScreenProps<
  RootStackParamList,
  'Main'
>;
  • 그럼 이건 어디에 사용되는 것일까? 뭐에 쓰지?
// 새로운 페이지를 정의해보고, props를 지정하자.
// 먼저 navigation과 route를 props로 받는데!
export default function PloggingPage({navigation, route}: PloggingScreenProps) {

...

//route는 특정 페이지에서 이동해왔을 때, 값을 받아오는데 사용!
useEffect(() => {
    if (route.params?.shouldOpenModal === true) {
      setModalVisible(true);
    }
  }, [route.params]);

...

// 아래와 같이 이동할 때 props에 페이지 이름을 추가해서 이동한다.
<Button
          title="Go to Plogging"
          onPress={() => navigation.navigate('Camera')}
        />
  • 되도록 타입은 types 폴더 안에 넣어서 import 해오는 습관 들이기!
profile
추상적인 생각을 구체적인 현실로

0개의 댓글