본문 바로가기
  • 삽질하는 자의 블로그
React/React-Route

2. React-Route의 기본 사용(2) v5

by 이게뭐당가 2022. 12. 20.

9. import { useRouteMatch } from "react-router-dom" [중첩 라우트 주소 간소화]

 

중첩된 라우트가 3개, 4개, 수십개 라고 생각해보자

 

<Route path="/xxx/yyy/zzz/ggg/hhh ..." >
	<Component/>
</Route>

중첩된 라우트의 최상위 path 를 변경하기 위해, 가장 앞의 "xxx" 를 "xxy" 로 고쳤다고 가정하자

 

자, 여기서 문제가 발생한다.

어떻게, 중첩된 라우트를 적는 것 까지는 그렇다 할 수 있다.

 

만약 바꾸려면?

 

하나하나 중첩된 모든 라우트를 찾아, 주소를 전부 변경해야한다.

 

useRouteMatch 를 사용하여, "현재 코드의 라우트 위치" 를 파악할 수 있다.

파악한 위치로, 중첩된 주소를 변경한다.

 

import { useRouteMatch } from "react-router-dom";

const Component = (props) => {
	const match = useRouteMatch()
    
    <Route path=`${match.url}/comment`>		// match.url 을 이용한다.
        <CommentComponent/>
    </Route>
}

match 의 안을 살펴보면

console.log(match)

    isExact: false			// 현 라우트가 exact 인지
    params: {quotesId: 'q2'}		// 현 라우트의 params
    path: "/quotes/:quotesId"		// 현 라우트의 path
    url: "/quotes/q2"			// 현 라우트의 URL

 

 

10. import { useLocation } from "react-router-dom"  [ 현재 내가 있는 URL 을 파악 ]

 

useLocation 은 현재 나의 URL 주소가 어떤지, 알려준다.

그리고 "쿼리 매개변수" 의 값을 알려준다. (search)

 

import { useLocation } from "react-router-dom";

const Component = (props) => {
	const location = useLocation()
    
 	console.log(location)
}

[http://localhost:3000/quotes]

    hash :  ""
    key: "bka7zu"
    pathname: "/quotes"
    search: ""
    state: undefined
    
[http://localhost:3000/quotes?ms=asb]

    hash: ""
    pathname: "/quotes"
    search: "?ms=asb"       // [쿼리 매개변수] search 에 값이 등록된다.
    state: undefined

 

 

11. useLocation 과 useRouteMatch 의 차이점과 활용법

 

차이점

useLocation 	=> URL 에 집중
useRouteMatch	=> 코드 위치 에 집중

 

예시

[조건]

APP => ITEM(동적) => ITME/COMMENT 순의 라우트가 정렬되어있다.

[http://localhost:3000/item/q2] 으로 접속하면
ITEM 만 렌더되지만

[http://localhost:3000/item/q2/comment] 로 접속하면
ITEM/COMMENT 는 ITEM 과 동시에 렌더 되도록 설정되어있다.

[코드]
    <item.js>

        const match = useRouteMatch()
        const location = useLocation()
        
        console.log(match)       
        console.log(location)

        <Route path = {`${math.url}/comment`}>
            <Comment />
        </Route>
        
 이때, [http://localhost:3000/item] 에 접속하면
 
	<결과>
        location.pathname: "/items/q2"     			==> 현재 URL 을 표기
        match.path: "/items/:itemId"             	==> 코드가 어디에 있는지 표기
        math.url : "/items/q2"
        
 하지만, [http://localhost:3000/item/comment] 로 접속하면
 
 	<결과>
        location.pathname: "/quotes/q2/comment"     ==> 현재 URL 을 표기
        match.path: "/items/:itemId"             	==> 코드가 어디에 있는지 표기
        math.url : "/items/q2"

활용법

match 		=> 중첩 path 의 주소를 적을때 보통 사용된다.
	match.url
    
location 	=> search 를 통한, 쿼리매개변수 사용시, 사용된다.
	location.search

 

12. import { useHistory } from "react-router-dom" [ 페이지의 변경 ]

 

usehistory 는 페이지 이동에 사용된다.

       import {useHistory} from "react-router-dom"

        const xxPage () =>{
            const history = useHistory()

            const submitHandler = (e) => {
                e.preventDefault();
            
                const quotes = {
                  id: idState,
                  author: authorState,
                  content: contentState,
                };
            
                dispatch(quotesActions.addQuotes({ quotes }));
            
                history.replace("/quotes");
              };
        }
        
 [옵션]
 
	history.replace		// 페이지 교체(뒤로가기 불가능)
    history.push		// 페이지 이동

 

 

 

13.  import { Redirect } from "react-router-dom"  [ 페이지의 강제 이동]

 

Redirect 는 Route에 의해 렌더되어, 특정 페이지로 이동시킨다.

 

<App.js>

    <Route exact path="/">                      // "/"  라고 입력하면
        <Redirect to="/welcome" />              // "welcome" 페이지로 이동한다.
    </Route>

 

댓글