- react router는 동적 url을 지원
- 동적 -> url에 변수를 넣을 수 있다는 의미
- :를 붙여줘야 함, 안그러면 진짜 텍스트임
- useParams -> 변수의 값을 넘겨줌
- await는 asyns함수 내부에 있지 않으면 사용할 수 없음
import {
BrowserRouter as Router,
Route,
Switch,
} from "react-router-dom";
import Detail from "./routes/Detail";
import Home from "./routes/Home";
function App() {
return (
<Router>
<Switch>
<Route path={"/hello"}>
<h1>Hello</h1>
</Route>
<Route path="/movie/:id">
<Detail />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
);
}
export default App;
import PropTypes from "prop-types";
import {Link} from "react-router-dom";
function Movie({ id, coverImage, title, summary, genres }) {
return (
<div>
<img src={coverImage} alt={title}/>
<h2>
<Link to={`/movie/${id}`}>{title}</Link>
</h2>
<p>{summary}</p>
<ul>
{genres.map((g) => (
<li key={g}>{g}</li>
))}
</ul>
</div>
);
}
Movie.propTypes = { //propTypes설정
id:PropTypes.number.isRequired,
coverImage: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
summary: PropTypes.string.isRequired,
genres: PropTypes.arrayOf(PropTypes.string).isRequired,
};
export default Movie;
import { useEffect } from "react";
import { useParams } from "react-router-dom";
import { useState } from "react";
function Detail(){
const [loading, setLoading] = useState(true);
const [movie, setMovies] = useState([]);
const {id} = useParams();
const getMovie = async() => {
const json = await( await fetch(`https://yts.mx/api/v2/movie_details.json?movie_id=${id}`))
.json(); //id를 알고 있으니 api로부터 정보를 fetch해올 수 있음
setMovies(json.data.movie);
setLoading(false);
};
useEffect(()=>{
getMovie();
},[])
console.log(movie);
return <div>{loading ? <h1>Loading...</h1> :
(<div>
<div>
<h1>{movie.title_long}</h1>
<img src={movie.medium_cover_image} alt={movie.title}/>
<h3>{movie.description_full}</h3>
</div>
</div>
)}
</div>;
}
export default Detail;