2022이전/React
REACT_SPA페이지구현(2)(match,location,history,withrouter)
바로퇴장
2020. 1. 28. 14:59
match,location,history
리액트에서 각 컴포넌트에서 props처럼 받는 데이터가 match, location,history에 들어 있다.
import React from 'react';
import queryString from 'query-string';
const About = ({location, match, history}) => {
const query = queryString.parse(location.search);
console.log(location);
console.log(match);
console.log(history);
...
- location
{pathname: "/about", search: "?key=value&key2=value2", hash: "", state: undefined}
location은 현재 페이지의 주소 상태를 알려줍니다.
- match
{path: "/about/:name?", url: "/about", isExact: true, params: {…}}
match는 <Route>컴포넌트에서 설정한 path와 관련된 데이터들을 조회할 때 사용합니다.
- history
About.js:7 {length: 6, action: "POP", location: {…}, createHref: ƒ, push: ƒ, …}
history는 현재 라우터를 조작할 때 사용합니다. 예를 들어 뒤쪽 페이지로 넘어가거나, 다시 앞쪽 페이지로 가거나, 새로운 주소로 이동해야 할 때 이 객체가. 지닌 함수들을 호출합니다.
위 세가지 props는 라우트로 사용된 컴포넌트에서만 접근할 수 있었습니다. 라우트 외부에 있는 라우터는 props를 사용하고 싶을 때 어떻게 할까요?
withRouter
import React from 'react';
import { NavLink, withRouter } from 'react-router-dom';
const Menu = () => {
const activeStyle = {
color: 'green',
fontSize: '2rem'
};
return (
<div>
<ul>
<li><NavLink exact to="/" activeStyle={activeStyle}>홈</NavLink></li>
<li><NavLink exact to="/about" activeStyle={activeStyle}>소개</NavLink></li>
<li><NavLink to="/about/react" activeStyle={activeStyle}>REACT 소개</NavLink></li>
</ul>
</div>
)
}
export default withRouter(Menu);
withRouter을 이용하여 export default withRouter(Menu)
처럼 withRouter을 감싸주면 위 세가지의 props를 사용할 수 있습니다.