파일 구조
/Routes/Detail/DetailContainer.js
DetailContainer.js
import React from "react";
import DetailPresenter from "./DetailPresenter";
export default class extends React.Component{
this.state = {
result:null,
error:null,
loading:true
};
render() {
console.log(this.props)
const {result, error, loading} = this.state;
return (
<DetailPresenter
result={result}
error={error}
loading={loading}
/>);
}
}
<Route path="/movie/:id" component={Detail} />
<Route path="/show/:id" component={Detail} />
DetailContainer.js
...
async componentDidMount() {
const {
match:{params:{id}},
history:{push},
location: {pathname}
} = this.props;
const parsedId = parseInt(id);
if(isNaN(parsedId)) {
// 홈으로 보내고 현재 함수를 종료시킨다 (return을 사용하는 이유)
return push("/");
}
...
-만일 전달 받은 id 값이 dddd 와 같은 string이라면(=isNaN) history 함수 중 push를 이용해서 페이지를 "/" 홈으로 보낸다
(왜냐면 movie, tv 둘 다 같은 컨포넌트를 바라보고 있기 때문에)
DetailContainer.js
...
export default class extends React.Component{
// state = {
// result:null,
// error:null,
// loading:true
// };
constructor(props){
super(props);
// 2.
const{location:{pathname}} = props;
this.state = {
result:null,
error:null,
loading:true,
isMovie: pathname.includes("/movie/")
};
}
async componentDidMount() {
const {
match:{params:{id}},
history:{push},
// location: {pathname}
} = this.props;
// 1. this.isMovie = pathname.includes("/movie/");
const {isMovie} = this.state;
const parsedId = parseInt(id);
if(isNaN(parsedId)) {
return push("/");
}
...
DetailContainer.js
...
export default class extends React.Component{
constructor(props){
super(props);
const{location:{pathname}} = props;
this.state = {
result:null,
error:null,
loading:true,
isMovie: pathname.includes("/movie/")
};
}
async componentDidMount() {
const {
match:{params:{id}},
history:{push}
} = this.props;
const {isMovie} = this.state;
const parsedId = parseInt(id);
if(isNaN(parsedId)) {
return push("/");
}
let result = null;
try {
if (isMovie) {
// const request = await movieApi.movieDetail(parsedId);
// result = request.data;
({ data : result } = await movieApi.movieDetail(parsedId))
} else {
// const request = await tvApi.movieDetail(parsedId);
// result = request.data;
({ data : result } = await tvApi.movieDetail(parsedId))
}
console.log(result)
} catch {
this.setState({error:"can't find anything"})
} finally {
this.setState({loading:false, result})
}
...