History
히스토리 API는 여러 자바스크립트 환경에서 세션 히스토리를 관리할 수 있는 패키지이다. 히스토리의 종류로는 다음 3가지가 있다.
보통 히스토리 객체는 browser history를 의미한다. browser history란 HTML5의 history API가 지원되는 브라우저에서 사용되는 히스토리 객체이다. history 객체는 또한 다음과 같은 속성을 가진다.
- length: 히스토리 스택의 사이즈
- action: 현재 액션 push, replace, pop
- location: 현재 location. location은 아래 속성을 가질 수 있다.
- pathname: (문자열)URL의 경로
- search: (문자열)URL의 쿼리 문자열
- hash: (문자열)URL의 해시부분
- state: (객체)
- push: 히스토리 스택에 새로운 엔트리를 푸시
- replace: 히스토리 스택의 현재 엔트리를 대체
히스토리 객체는 변화가능하다. 따라서 location은 Route의 렌더 props으로 부터 받아쓰도록 하자.
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
Location
location은 현재 앱이 어디있는지, 어디에서 왔는지, 어디로 갈지에 대한 표현이다.
{
key: 'ac3df4', // not with HashHistory!
pathname: '/somewhere',
search: '?some=search-string',
hash: '#howdy',
state: {
[userDefined]: true
}
}
라우터는 특정 방식을 통해 location객체를 전달한다.
- Route component; this.props.location
- Route render; ({location})=>()
- Route children; ({location})=>()
history.location을 통해서도 접근이 가능하지만 history객체는 mutable하기 때문에 이런식의 접근은 권장되지 않는다.
location 객체는 immutable하기 때문에 라이프사이클 훅에 편하게 사용해도 된다.
Match
Match객체는 <Route path>가 어떻게 URL에 대응되는지에 대한 정보를 담고있다. match 객체는 다음과 같은 속성을 지닌다.
- params: [객체] URL에서 파싱된 경로의 동적세그먼트에 대응하는 key/value 짝
- isExact: [boolean] 전체 URL과 일치하는지에 대한 정보(뒤에 붙는 문자는 괜찮?)
- path: [문자열] match에 사용된 경로패턴. nested <Route>으로 응용된다.
- url: [문자열] URL과 일치하는 부분. nested <Link>으로 응용된다.
match 객체는 다음과 같은 방식으로 접근할 수 있다.
- Route component; this.props.match
- Route render; ({match})=>()
- Route children; ({match})=>()
- withRouter; this.props.match
Route에 경로가 없을때는 항상 match가 된다. 이런 경우에는 가장 가까운 부모 match가 적용된다.
Route에 children props을 이용할 경우 경로가 없더라도 children function을 호출한다. 이런 경우 match는 null이 된다.
'Frontend > JavaScript' 카테고리의 다른 글
Sync vs Async (0) | 2021.09.27 |
---|---|
JEST (0) | 2021.08.31 |
프론트 비동기 작업 이해하기(feat. React) (0) | 2021.07.03 |
2020-05-21 :: Promise (0) | 2021.05.21 |
200824 (0) | 2020.08.24 |