React Router 공식문서 번역 및 정리

Junghyun Park·2021년 5월 3일
0

React Router 공식문서

APIs

Hooks

useHistory()

props.history와 동일

useLocation()

props.Location과 동일

useParams()

props.match.params와 동일

useRouteMatch()

string 형태의 path 또는 object 형태의 인자를 받아서, match data에 접근하고 이를 포함한 함수를 구현하기 위한 사용

< MemoryRouter >

메모리에 저장되어 있는 URL history를 담고 있음

<MemoryRouter
  initialEntries={optionalArray}
  initialIndex={optionalNumber}
  getUserConfirmation={optionalFunc}
  keyLength={optionalNumber}

  <App />
</MemoryRouter>

< Prompt >

어떤 페이지로부터 떠나기 전 Prompt 창을 유저에게 보여줌

<Prompt
  when={formIsHalfFilledOut}
  message="Are you sure you want to leave?"
/>
  • when : (boolean) "true"일때 prompt 실행/ "false"일때 실행 x
  • messeage: prompt 창에 보여주는 메시지, 함수로도 작성가능

< Redirect >

  • 새로운 location으로 이동
  • 새로운 location은 history stack에서 현재 location에 override됨
<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>
====================== 
<Redirect
  to={{
    pathname: "/login",
    search: "?utm=your+face",
    state: { referrer: currentLocation }
  }}
/>
  • push : (bool) true이면, override(replace)하지 않고 추가(push)하여 페이지 이동
<Redirect push to="/somewhere/else" />
  • from : 이동하기 전 현재 페이지 주소 / Switch 문 내부에서만 작동
<Switch>
  <Redirect from="/users/:id" to="/users/profile/:id" />
  <Route path="/users/profile/:id">
    <Profile />
  </Route>
</Switch>
  • exact: (bool) 주소가 정확히 일치하는 경우에만 적용/ Switch 문 내부에서만 작동
  • strict: (bool) 주소가 엄격하게 일치하는 경우에만 적용 / Switch 문 내부에서만 작동
  • sensitive : (bool) case sensitive 여부

< Route >

  • React Route에서 가장 중요한 컴포넌트
  • 가장 기본적인 기능은 URL 주소의 일치여부에 따라 페이지 전환(UI 랜더링)
  • 해당 컴포넌트를 랜더링하는 Route의 함수는 Route 태그 내부에 children으로 삽입하는 방법이 가장 권장되지만 추가적으로 아래와 같은 함수가 존재 (이 중 하나만 사용해야 함)
    i) <Route componenet> => 매번 새로 생성(React.createElement) 되는 비효율 발생
    ii) <Route render> => path가 match되는 경우에 한하여 랜더링
    iii) <Route children> function => path의 매치여부에 관계없이 랜더링

Route props

Route의 모든 랜더링 함수에는 아래의 3개의 props를 자동으로 전달

1. match

  • 어떻게 <Route path>와 match 시킬 건지에 대한 정보를 포함하는 object
    i) params(object): 이동하는 URL에서 넘어온 key/value 형식의 데이터 ('~:id')
    ii) isExact(boolean): 전체 URL이 일치하면 true
    iii) path(string): match(비교)에 사용된 path pattern
    iv) url(stirng): URL에서 match 되는 부분

2. location

  • app의 어디에 현재 위치하는지, 어디로 갈예정이고, 어디에 있었는지에 대한 정보
  • history와 달리 location object는 not mutable이므로, data fetching이나 animation에 유용하게 사용가능
{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere',
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}

3. history

  • history object는 아래와 같은 properties와 methods를 가지고 있음
  • hitory object는 'mutable'이므로, history.location이 아니라 props.location으로 접근해야 함
  • length - (number) The number of entries in the history stack
  • action - (string) The current action (PUSH, REPLACE, or POP)
  • location - (object) The current location. May have the following properties:
    i) pathname - (string) The path of the URL
    ii) search - (string) The URL query string
    iii) hash - (string) The URL hash fragment
    iv) state - (object) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
  • go(n) - (function) Moves the pointer in the history stack by n entries
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation (see the history docs)

< Router >

  • The common low-level interface for all router components.
  • Typically apps will use one of the high-level routers instead:

    <BrowserRouter>
    <HashRouter>
    <MemoryRouter>
    <NativeRouter>
    <StaticRouter>

  • low-level Router를 사용하는 가장 일반적인 case는 synchronize a custom history with a state management lib like Redux or Mobx.

< Static Router >

  • location이 바뀌지 않는 Router

< Switch >

  • location과 match되는 태그 안의 첫번째 child(<Routes> or <Router>)를 랜더

withRouter

Router 나 Route에 등록되어있지 않은 컴포넌트에서 그 부모의 props를 전달받아 사용할 수 있도록 하기 위하여 사용

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

generatePath

  • The generatePath function can be used to generate URLs to the routes.
import { generatePath } from "react-router";
generatePath("/user/:id/:entity(posts|comments)", {
  id: 1,
  entity: "posts"
});
// Will return /user/1/posts
profile
21c Carpenter

0개의 댓글