YIL - React route parameters

김현재·2021년 9월 8일
0
post-thumbnail

라우트의 props

라우트로 설정한 컴포넌트는 3가지 props를 전달받는다

history

이 객체를 통해 push, replace 를 사용하여 다른 경로로 이동하거나 앞, 뒤 페이지로 전환할 수 있다.

주의

[this.props.match.params.id](http://this.props.match.params.id) 는 문자 형태이기에 페이지 이동을 위해 연산을 해야하는 경우 Number() 를 사용하자!

goNext = () => {
    this.props.history.push(
			`/monsters/detail/${Number(this.props.match.params.id) + 1}`
		);
  };

location

현재 url 경로에 대한 정보를 지니고 있고, URL 쿼리 (/about?foo=bar) 정보도 가지고 있다

match

어떤 라우트에 매칭이 되었는지에 대한 정보가 있고, path parameter(/about/:name) 정보를 가지고 있다

params를 활용하여 필요한 정보를 추출해와 사용하기도 한다.

componentDidMount() {
	**fetch(`${API}/${this.props.match.params.id}`)**
	.then(res => res.json())
	.then(res => ...);

위와 같이 현재 path에 대한 정보만 추출이 가능하기에, 페이지가 넘어간 이후 해당 id에 대한 정보를 서버에 요청할 수 있다.

profile
쉽게만 살아가면 재미없어 빙고!

0개의 댓글