-
Notifications
You must be signed in to change notification settings - Fork 5
react_router
๊น์์ง edited this page Nov 7, 2020
·
3 revisions
- ๋ค๋ฅธ ์ฃผ์์ ๋ฐ๋ผ ๋ค๋ฅธ ๋ทฐ๋ฅผ ๋ณด์ฌ์ฃผ๋ ๊ฒ์ ๋ผ์ฐํ ์ด๋ผ๊ณ ํ๋ค.
- React ์์ฒด์๋ ์ด ๊ธฐ๋ฅ์ด ๋ด์ฅ๋์ด์์ง ์๊ธฐ ๋๋ฌธ์ ์ฐ๋ฆฌ๊ฐ ์ง์ ๋ธ๋ผ์ฐ์ ์ API๋ฅผ ์ฌ์ฉํ๊ณ ์ํ๋ฅผ ์ค์ ํ์ฌ ๋ค๋ฅธ ๋ทฐ๋ฅผ ๋ณด์ฌ์ฃผ์ด์ผ ํ๋ค.
- react-router ์ค์นํ๊ธฐ
npm i react-router-dom
- react-router๋ ์จ๋ํํฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ก์, ๊ณต์ ๋ผ์ฐํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ์๋์ง๋ง ๋ฆฌ์กํธ ๋ผ์ฐํ ์ ๊ฐ์ฅ ๋ง์ด ์ฌ์ฉ๋๊ณ ์๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ด๋ค.
- ํด๋ผ์ด์ธํธ ์ฌ์ด๋์์ ์ด๋ค์ง๋ ๋ผ์ฐํ ์ ๊ฐ๋จํ๊ฒ ํด์ค๋ค.
- ์๋ฒ ์ฌ์ด๋ ๋ ๋๋ง๋ ๋์์ฃผ๋ ๋๊ตฌ๋ค์ด ํจ๊ป ๋ธ๋ ค์จ๋ค.
-
<BrowserRouter />
: HTML5 history API๋ฅผ ์ฌ์ฉํ์ฌ ์ฃผ์๋ฅผ ๊ด๋ฆฌํ๋ ๋ผ์ฐํฐ -
<Route />
: ์์ฒญ ๊ฒฝ๋ก์ ๋ ๋๋งํ ์ปดํฌ๋ํธ ์ค์ -
<Switch />
: ํ์์ ๋ผ์ฐํฐ ์ค ํ๋๋ฅผ ์ ํ- ๋ผ์ฐํธ๋ค์ ์ด ์ปดํฌ๋ํธ์ ๊ฐ์ธ๋ฉด ๋งค์นญ๋๋ ์ฒซ๋ฒ์งธ ๋ผ์ฐํธ๋ง ๋ณด์ฌ์ฃผ๊ณ ๋๋จธ์ง๋ ๋ณด์ฌ์ฃผ์ง ์๋๋ค.
- switch๋ฅผ ์ฌ์ฉํ๋ฉด
exact
๋ฅผ ์ฌ์ฉํ์ง ์์๋ ๋จ
-
<Redirect />
: ์์ฒญ ๊ฒฝ๋ก๋ฅผ ๋ค๋ฅธ ๊ฒฝ๋ก๋ก ๋ฆฌ๋ค์ด๋ ์ - ์์ ์ฝ๋
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { Home, About, Posts } from 'pages';
import Menu from 'components/Menu';
function App() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about/:name" component={About}/>
<Route path="/about" component={About}/>
<Redirect path="*" to="/" />
</Switch>
</BrowserRouter>
);
}
export default App;