반응형
SMALL
6.4 Redirecting
<Detail.js>
function Detail({location}){ console.log(location); return <span> Hello </span>; }
문제
- location의 props들이 console에 나타나지만 poster를 눌러서 movie-detail에 들어간 경로가 아닌 url에 /movie-detail이라고 쳐서 들어간 경우, state가 undefined라고 뜸
해결 방법
import React from 'react';
class Detail extends React.Component{
componentDidMount(){
const{location,history}=this.props;
if(location.state===undefined){
history.push("/"); //redirect
}
}
render(){
const{location}=this.props;
return <span>{location.state.title}</span>;
}
}
export default Detail;
- location에서 state가 undefined일 경우, history의 push 경로를 "/"으로 변경시켜 Home으로 가게 만듦
-문제 : poster을 누르면 location.state.title이 뜨지만, 새로고침하면 error가 뜸
- 이유: render() 이후, componentDidMount()이 실행되는데 새로고침을 하면 componentDidMount()에서 if문이 실행되기전이여서 render()함수가 실행될 때 location.state가 undefined된 상태여서location이 존재하지않기 때문
해결 방법
if(location.state){ return <span>{location.state.title}</span>; } else{ return null; }
반응형
LIST
'Web 강의 > ReactJS로 영화 웹 서비스 만들기' 카테고리의 다른 글
[노마드코더/ReactJS로 영화 웹 서비스 만들기]6.3 Sharing Props Between Routes (0) | 2022.03.23 |
---|---|
[노마드코더/ReactJS로 영화 웹 서비스 만들기] 6.2 Building the Navigation (0) | 2022.03.23 |
[노마드코더/ReactJS로 영화 웹 서비스 만들기]6.0 Getting Ready for the Router (0) | 2022.03.23 |
[노마드코더/ReactJS로 영화 웹 서비스 만들기]6.1 Building the Router (0) | 2022.03.23 |
[노마드코더/ReactJS로 영화 웹 서비스 만들기]5.0 Deploying to Github Pages & 5.1 Are we done? (0) | 2022.03.23 |