리다이랙트 기능 만들어 보기
리다이랙트 기능을 위해서는 route props의 history 키를 활용해야 합니다. history 키에는 push, go, goBack, goForward와 같은 키가 있는데 그 키에는 URL을 변경해주는 함수들이 들어 있습니다.
history 키 살펴보기
주소 창에 localhost:3000를 입력해서 이동한 다음 아무 영화 카드나 눌러 이동합니다. 그런 다음 [Console] 탭에서 [history]에 출력된 값을 펼쳐서 살펴봅시다.
push, go, goBack, goForward 키가 URL을 변경해주는 함수입니다.
Detail 컴포넌트 클래스형 컴포넌트 변경하기
Detail 컴포넌트를 함수형에서 클래스형 컴포넌트로 변경한 다음 location, history 키를 구조 분해 할당합니다.
import React from "react";
class Detail extends React.Component {
componentDidMount() {
const { location, history } = this.props;
}
render() {
return <span>hello</span>;
}
}
export default Detail;
사용자가 URL을 직접 입력해서 /movie-detal로 이동하면 location 키의 state 키가 비어 있습니다. 그런 경우에만 history 키의 push() 함수를 사용할 것입니다.
push() 함수 사용하기
import React from "react";
class Detail extends React.Component {
componentDidMount() {
const { location, history } = this.props;
if (location.state === undefined) {
history.push("/");
}
}
render() {
return <span>hello</span>;
}
}
export default Detail;
리다이렉트 기능 확인해 보기
영화 앱을 실행한 다음 직접 주소를 입력해서 /movie-detail으로 이동해봅시다. 그러면 다시 Home으로 돌아오게 될겁니다.
영화 제목 출력하기
우선 영화 제목부터 출력해 봅시다. Movie 컴포넌트로부터 전달받은 영화 데이터는 location.state에 들어 있습니다.
import React from "react";
class Detail extends React.Component {
componentDidMount() {
const { location, history } = this.props;
if (location.state === undefined) {
history.push("/");
}
}
render() {
const { location } = this.props;
if (location.state) {
return <span>{location.state.title}</span>;
}
}
}
export default Detail;
/movie-detail로 바로 이동하기
render() 함수 내에서 location.state.title을 사용하려 하는데, location.state가 아까와 마찬기지로 undefined이가 때문입니다. 그로니까 render() 함수에도 componentDidMount() 생명주기 함수에 작성한 리다이랙트 코드를 추가해 주어야 합니다.
location.state 확인하기
location.state가 없으면 render() 함수가 null을 반환하도록 수정합시다.
import React from "react";
class Detail extends React.Component {
componentDidMount() {
const { location, history } = this.props;
if (location.state === undefined) {
history.push("/");
}
}
render() {
const { location } = this.props;
if (location.state) {
return <span>{location.state.title}</span>;
} else {
return null;
}
}
}
export default Detail;
location.state가 없으면 render() 함수가 null을 반환하도록 만들어서 문제 없이 실행하도록 만든것입니다. 그러면 이어서 componentDisMount() 생명주기 함수가 실행되면서 리다이랙트 기능이 동작할 것입니다.
'프로그래밍 언어 > REACT' 카테고리의 다른 글
| 영화 앱 깃허브에 배포하기 (0) | 2025.02.26 |
|---|---|
| 영화 상세 정보 기능 만들어 보기 (0) | 2025.02.20 |
| 내비게이션 만들어 보기 (0) | 2025.02.17 |
| 라우터 만들어 보기 (0) | 2025.02.14 |
| react-router-dom 설치하고 프로젝트 폴더 정리하기 (0) | 2025.02.11 |