2022. 9. 26. 15:27ㆍReact/ReactJS로 영화 웹 서비스 만들기
우리는 링크를 통해 정보를 라우터로 보내고있다.
그래서 콘솔창을 본다면
자 그럼 props가 아니라 location으로 바꿔서 한번 전달해보자.
근데 undefined가 나오게 된다.
클릭 없이 아래의 링크로 접속하게 된다면 undefined가 나오게되는 상황이 벌어진것이다.
http://localhost:3000/#/movie-detail
이를 해결해보자.
그래서 클래스 컴포넌트로 작성하면
import React from "react";
class Detail extends React.Component {
componentDidMount() {
const { location } = this.props;
console.log(location.state);
}
render() {
return <span>hello</span>;
}
}
export default Detail;
다음과 같이 undefined가 된다.
그래서 다음과 같이 수정해보자.
그냥 이 링크로 접속만 하게 된다면 Home으로 다시 redirect할 수 있도록!
먼저 props를 출력해보면
go, goback등 장소를 바꿀 수 있도록해주는것을 볼 수 있다.
그래서 history까지 가져와보자.
undefined이면 home으로 가도록!
http://localhost:3000/movie-detail
페이지로 이동하게 되면, 바로 home으로 이동하는 것을 확인할 수 있다.
home에서 영화를 클릭하면 정상적으로 작동되지만,
http://localhost:3000/movie-detail 로 direct로 접속하면 바로 home으로 이동하게 된다.(redirect)
그럼 정상적으로 작동되는 것을 확인할 수 있다.
근데 위 링크를 다시한번 엔터를 쳐서 접속하게된다면
다음과 같은 에러가 나게 된다.
location이 존재하지 않기때문이다!
아래가 실행되고
render() {
const { location } = this.props;
return <span>{location.state.title}</span>;
}
아래가 실행되는데
componentDidMount() {
const { location, history } = this.props;
if (location.state === undefined) {
history.push("/");
}
}
location이 존재하지않으면 에러가날 것이기때문!
그래서 아래와 같이 고치게된다면
render부분이 끝나고 우리는 home으로 다시 돌아가게된다.(componentDidMount)
혹, 더 좋은 방법으로 하자면!
다음과 같이 수정해보자.
App.js
Movie.js
그럼 다음과 같이 30440처럼 id를 가져오게 된다.
'React > ReactJS로 영화 웹 서비스 만들기' 카테고리의 다른 글
14.3 Sharing Props Between Routes (2) | 2022.09.26 |
---|---|
14.2 Building the Navigation (2) | 2022.09.23 |
14.1 Building the Router (0) | 2022.09.23 |
14.0 Getting Ready for the Router (0) | 2022.09.23 |
13.1 Are we done? (2) | 2022.09.23 |