[TIL] React - Router

Dev_minยท2019๋…„ 10์›” 6์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
11/61

๐Ÿ‘‰ Todolist side-project

todolist side project ์ง„ํ–‰์„ ํ•˜๊ณ  ์žˆ๋Š”๋ฐ, ์ฒ˜์Œ ์‹œ์ž‘ํ•  ๋•Œ ํ”„๋กœ์ ํŠธ ๊ตฌ์กฐ๋ฅผ ์ƒ๊ฐํ•˜๋Š” ๊ฒƒ์ด ์–ด๋ ต๊ณ , ์–ด๋–ค component๋กœ ๊ตฌ์„ฑํ• ์ง€๊ฐ€ ์–ด๋ ค์šด ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.

๐Ÿ”จ React-Router

์—ฌ๋Ÿฌ ํ™”๋ฉด์ด ๊ตฌ์„ฑ๋œ ์›น ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ๋งŒ๋“ ๋‹ค๋ฉด ํ•„์ˆ˜์ ์ธ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ด๋ฉฐ, React-native์—๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
์‚ฌ์šฉ์ž๊ฐ€ ์›ํ•˜๋Š” ํŽ˜์ด์ง€๋กœ ์ด๋™์„ ์›ํ•˜๊ฒŒ ๋˜๋Š”๋ฐ, ํ•ด๋‹น ํŽ˜์ด์ง€๋กœ ์ด๋™์„ ๊ฐ€๋Šฅ์ผ€ํ•˜๋Š” ๊ฒƒ์ด Router์˜ ์—ญํ• 

๋ผ์šฐํŒ… : ๋‹ค๋ฅธ ์ฃผ์†Œ์— ๋”ฐ๋ผ ๋‹ค๋ฅธ ๋ทฐ๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ๊ฒƒ
SPA : Single Page Application - ํŽ˜์ด์ง€๊ฐ€ 1๊ฐœ์ธ ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜

๐Ÿงฑ Hash Router

ํด๋ผ์ด์–ธํŠธ๋ฅผ ์œ„ํ•ด ์„ค๊ณ„๋œ ๋ผ์šฐํ„ฐ. Hash(#)๋Š” ์•ต์ปค๋งํฌ๋ฅผ ์ •์˜ํ•  ๋•Œ ์‚ฌ์šฉ. ์ฃผ์†Œ์ฐฝ์˜ ํ˜„์žฌ ํŽ˜์ด์ง€ ๊ฒฝ๋กœ ๋’ค์— # ์‹๋ณ„์ž๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ๋ธŒ๋ผ์šฐ์ €๋Š” ์„œ๋ฒ„ ์š”์ฒญ์„ ๋ณด๋‚ด์ง€ ์•Š๊ณ , ํ˜„์žฌ ํŽ˜์ด์ง€์—์„œ ์‹๋ณ„์ž์— ํ•ด๋‹นํ•˜๋Š” id attribute๊ฐ€ ์žˆ๋Š” element๋ฅผ ์ฐพ์•„์„œ ๊ทธ element์˜ ์œ„์น˜๋ฅผ ํ™”๋ฉด์— ๋ณด์—ฌ์ค€๋‹ค.
๋ชจ๋“  ๊ฒฝ๋กœ ์•ž์— #๋ฅผ ๋ถ™์—ฌ์•ผ ํ•œ๋‹ค ๋ฐฑ์—”๋“œ๊ฐ€ ํ•„์š” ์—†๋Š” ์ž‘์€ ํด๋ผ์ด์–ธํŠธ ์‚ฌ์ดํŠธ๋ฅผ ๋งŒ๋“ค ๋•Œ ์œ ์šฉํ•œ ๋„๊ตฌ

import React from "react";
import {
  HashRouter as Router,
  Route,
  Redirect,
  Switch
} from "react-router-dom";
import CurrentList from "../Page/CurrentList";
import PastList from "../Page/PastList";

export default () => (
  <Router>
    <Switch>
      <Route path="/" exact component={CurrentList} />
      <Route path="/pastlist" exact component={PastList} />
      <Redirect from="*" to="/" />
    </Switch>
  </Router>
);
// exact๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ  -> ์ฃผ์–ด์ง„ ์ฃผ์†Œ์™€ ๊ฐ™์•„์•ผ render๊ฐ€ ์ง„ํ–‰

๐Ÿงฑ BrowserRouter

์‹ค์ œ Browser ์ฃผ์†Œ์™€ ๊ฐ™์€ ํ˜•ํƒœ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค. ์•ฑ์„ router๋กœ ๊ฐ์‹ธ๋ฉด router๊ฐ€ history api ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๊ณ , Route๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ match, history, location ๋“ฑ์˜ props๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๐Ÿงฑ Switch

์Šค์œ„์น˜๋Š” ๋ผ์šฐํ„ฐ๋“ค์„ ๋ฌถ์€ ๋‹ค์Œ, ๊ฐ€์žฅ ๋จผ์ € path์— ๋งค์น˜๋˜๋Š” Route์— ์—ฐ๊ฒฐ

๐Ÿงฑ Redirect

Redirect์˜ ๊ฒฝ์šฐ์—๋Š” ํ•ด๋‹น๋˜์ง€ ์•Š์€ ์ฃผ์†Œ๊ฐ€ ์ž…๋ ฅ์‹œ ์ •ํ•œ ์ฃผ์†Œ๋กœ ํŽ˜์ด์ง€๋ฅผ ๋ณด๋‚ด์ฃผ๋Š” ๊ฒƒ์ด๋‹ค. ์—ฌ๊ธฐ์„œ์˜ redirect๋Š” push๊ฐ€ ์•„๋‹Œ replace๋ฐฉ์‹์ด๋ผ history์— ๋‚จ์ง€ ์•Š๋Š”๋‹ค. location ๊ฐ์ฒด๋ฅผ ํ†ตํ•ด์„œ๋„ redirect๊ฐ€ ๊ฐ€๋Šฅ

< React-Router https://reacttraining.com/react-router/web/guides/quick-start >

profile
TIL record

0๊ฐœ์˜ ๋Œ“๊ธ€