티스토리 뷰
Route에 path 속성에 아무것도 전달하지 않으면 어떻게 될까요?
switch를 알아보기 우선은 Route에 path 속성 값을 전달하지 않으면 어떻게 되는지 부터 알아봅시다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { Route } from "react-router-dom"; | |
const App = () => { | |
return ( | |
<div> | |
<Route path="/" component={Home} /> | |
<Route path="/about" component={About} /> | |
<Route component={NotFound} /> | |
</div> | |
); | |
}; | |
const Home = () => { | |
return <h1>Home!</h1>; | |
}; | |
const About = () => { | |
return <h1>About me!</h1>; | |
}; | |
const NotFound = () => { | |
return <h1>Not Found!</h1>; | |
}; | |
export default App; |
해당 예시에는 3개의 라우트가 있고, 맨 마지막 라우트에는 path 속성을 전달하지 않았습니다.
path 속성을 전달하지 않았습니다.
결과는 "localhost:3000/"에 접속하니 path 값이 "/"인 Home 컴포넌트와 path 값이 없는 NotFound 컴포넌트가 둘 다 보이는 군요. 즉 path를 전달하지 않으면 어떤 요청에도 항상 나타나게 됩니다. "localhost:3000/about"에 접속하면 우리가 설정한 세 개의 컴포넌트가 다 보이게 됩니다. 이럴 때 스위치를 사용하시면 됩니다.
switch 사용해보기
스위치는 라우터들을 묶은 다음, 가장 먼저 path에 매치되는 Route에 연결시킵니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Route, Switch } from "react-router-dom"; | |
const App = () => { | |
return ( | |
<div> | |
<Switch> | |
<Route exact path="/" component={Home} /> | |
<Route path="/about" component={About} /> | |
<Route component={NotFound} /> | |
</Switch> | |
</div> | |
); | |
}; |
해당 코드처럼 Switch 컴포넌트를 불러온 다음 Route 들을 감싸주세요. 그리고 첫 번째 Route에는 exact를 추가했습니다. 이제 다시 앱을 실행시켜보세요. "/"에도, "/about"에도 하나만 나타납니다. 또 우리가 path를 전달하지 않은 컴포넌트는 어떻게 될까요? 위 두 설정에서 라우트를 찾을 수 없다면 항상 Not Found라는 말이 나타납니다. switch를 통해 404 페이지를 만든 것이죠!
이처럼 적절한 switch 사용으로 좀 더 깔끔한 코드를 작성할 수 있습니다.
공감은 제작자에게 큰 힘이 됩니다.
'Frontend-dev > react' 카테고리의 다른 글
리액트스트랩 시작하기 (0) | 2019.01.03 |
---|---|
react-native의 세팅을 도와주는 expo 이용해보기 (0) | 2018.12.23 |
리액트 라우터로 path와 querystring 받아오기 (0) | 2018.12.06 |
리액트의 라우터 v4를 알아봅시다. (0) | 2018.12.06 |
예제를 통해 리덕스(redux)를 연습해봅시다. (0) | 2018.11.27 |