공부하는 블로그

React | Router : match, location, history 본문

React

React | Router : match, location, history

치킨닮은닭 2020. 1. 17. 19:57

Router Props

 브라우저와 리액트앱의 라우터를 연결하게 되면 그 결과 라우터가 history api에 접근할 수 있게 되며 각각의 Route와 연결된 컴포넌트에 props로 match, location, history라는 객체를 전달하게 된다.

 

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
import Home from './components/home';
import Community from './components/community';
import Mypage from './components/mypage';



function App() {
  return (
    <div className="App">
      <Router>
        <div className='Menu-wrapper'>
          <ul>
            <Link to='/'><li>Home</li></Link>
            <Link to='/community'><li>Community</li></Link>
            <Link to='/mypage'><li>MyPage</li></Link>
          </ul>
        </div>
        <div className='Contents-wrapper'>
          <Switch>
            <Route exact path='/' component={Home} />
            <Route path='/community' component={Community} />
            <Route path='/mypage' component={Mypage} />
          </Switch>
        </div>
      </Router>
    </div>
  );
}

export default App;

 

// home.js

import React from 'react';

class Home extends React.Component {
  render() {
    console.log(this.props);
    
    return(
      <h1>This is Home Component</h1>
    )
  }
}

export default Home

 

 간단하게 라우팅을 한 후 연결된 컴포넌트에서 콘솔로 props를 확인해보았다.

 

console.log(this.props)

 반환된 객체(props)에서 history, location, match가 담겨있는 것을 확인할 수 있다.

 

Match

 match 객체에는 <Route path>와 URL이 매칭된 대한 정보가 담겨져있다. 대표적으로 match.params로 path에 설정한 파라미터값을 가져올 수 있다.

 

console.log(this.props.match)

 

·path : [string] 라우터에 정의된 path

· url : [string] 실제 클라이언트로부터 요청된 url path

· isExact : [boolean] true일 경우 전체 경로가 완전히 매칭될 경우에만 요청을 수행

· params : [JSON object] url path로 전달된 파라미터 객체 

Location

 location 객체에는 현재 페이지의 정보를 가지고 있다. 대표적으로 location.search로 현재 url의 쿼리 스트링을 가져올 수 있다.

 

요청 URL
console.log(this.props.location)

 

· pathname : [string] 현재 페이지의 경로명

· search : [string] 현재 페이지의 query string

· hash : [string] 현재 페이지의 hash

 

History

 history 객체는 브라우저의 history와 유사하다. 스택(stack)에 현재까지 이동한 url 경로들이 담겨있는 형태로 주소를 임의로 변경하거나 되돌아갈 수 있도록 해준다.

 

console.log(this.props.history)

 

· length : [number] 전체 history 스택의 길이

· action : [string] 최근에 수행된 action (PUSH, REPLACE or POP)

· location : [JSON object] 최근 경로 정보

· push(path, [state]) : [function] 새로운 경로를 history 스택으로 푸시하여 페이지를 이동

· replace(path, [state]) : [function] 최근 경로를 history 스택에서 교체하여 페이지를 이동

· go(n) : [function] : history 스택의 포인터를 n번째로 이동

· goBack() : [function] 이전 페이지로 이동

· goForward() : [function] 앞 페이지로 이동

· block(prompt) : [function] history 스택의 PUSH/POP 동작을 제어


Reference

 

· https://www.freecodecamp.org/news/hitchhikers-guide-to-react-router-v4-4b12e369d10/

· https://medium.com/@han7096/react-router-v4-%EC%A0%95%EB%A6%AC-e9931b63dcae

'React' 카테고리의 다른 글

React | Iterator : Array.map()  (0) 2020.01.17
React | Router : URL로 parameter 전송하기  (0) 2020.01.17
React | Router : URL로 페이지 접근하기  (1) 2020.01.11
React | Form  (0) 2020.01.11
React | Event Handling  (0) 2020.01.10
Comments