[노마드코더] React - 영화 웹 서비스 만들기 연습

김지원·2023년 1월 13일
0

Frontend

목록 보기
9/27

💡 async-await 함수

보편적으로 fetch 대신 async-await를 사용한다.

  useEffect(()=>{
    fetch('https://yts.mx/api/v2/list_movies.json?minimum_rating=9&sort_by=year')
      .then((response)=>response.json())
      .then((json) =>
        setMovies(json.data.movies));
        setLoading(false);
  }, []);

대신

  const getMovies = async() => {
    const response = await fetch('https://yts.mx/api/v2/list_movies.json?minimum_rating=9&sort_by=year');
    const json = await response.json();
    //또는
    const json = await ( await fetch('https://yts.mx/api/v2/list_movies.json?minimum_rating=9&sort_by=year')).json();
 }
 useEffect(()=>{
   getMoveis();
 }, []);

💡 map 함수 복습

[1, 2, 3, 4, 5].map(x => x**2)
// [1, 4, 9, 16, 25]

굉장히 중요 👉 key, 고유한 값을 주어야 한다!!!
key는 React.js에서 map 안에서 component들을 render할 때 사용하는 것이다.

api로 불러온 영화들의 제목들을 보여주려면?

  return (
  <div>
    {loading ? <h1>Loading...</h1> : 
      <div>
        {movies.map(movie => 
             <div key={movie.id}>
                   {movie.title}
             </div>
        )}
      </div>}
  </div>

api로 불러온 영화들의 장르를 보여주려면?

<ul>
  {movie.genres.map(g => (
    <li key={g}>{g}</li>
  ))}
</ul> 

❗ 내가 겪은 에러

Uncaught Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead.

//function Movie(coverImg, title, summary, genres) 가 아니라 아래처럼 {} 필요
function Movie({coverImg, title, summary, genres})

💡 Components를 사용하여 코드 정리하기

💡 Router - 다른 페이지로 이동하기

react-router-dom v6 설치한다.

npm install react-router-dom@6
import {
  BrowserRouter as Router,
  Routes,
  Route,
} from "react-router-dom";
import Home from "./routes/Home";

function App() {
  return <Router>
    <Routes>
      <Route path="/">
        // Home 컴포넌트를 렌더링 한다.
        <Home />
      </Route>
      <Route path="/movie">
        <Detail />
      </Route>
    </Routes>
  </Router>
}
  • ⌨️Router: 유저가 있는 url에 따라서 다른 컴포넌트를 보여주기 위함이다.
  • ⌨️Routes: 한 번에 하나의 Route만 렌더링하기 위해 사용한다. Router에서는 두 개의 Route를 한 번에 렌더링할 수 있다.

❓ Browser Router과 Router의 차이점

Browser Router에서의 URL는 보통의 웹사이트처럼 생겼다. 대부분 Browser Router을 사용한다.

localhost:3000/movie

HashRouter의 경우,

localhost:3000/#/movie

Link를 사용하여 브라우저 새로고침 없이도 유저를 다른 페이지로 이동시킬수 있다.

<h2>
  <Link to="/movie">{title}</Link>
</h2> 

📌 동적(dynamic) url 지원

예를 들어 /movie/:id 처럼 변수를 넣을 수 있다.
주의할 점은 /movie/id 가 아닌 /movie/:id !

<Link to={`/movie/${id}`}>{title}</Link>

http://localhost:3000/movie/48017
여기에서 48017이 무슨 id인지 어떻게 알 수 있을까?

👉👉 useParams 를 import

import {useParams} from "react-router-dom";

function Detail() {
    const x = useParams();
    console.log(x);
    return <h1>Detail</h1>
}

✨ Publishing

npm i gh-pages
npm run build

build라는 폴더가 생긴다. 이 build 를 git page에 push하면 된다.

package.json 파일에 아래 줄을 추가해준다.

"homepage": "https://{github-user-id}/github.io/{github-repository}"

그리고 "scripts" 아래

    "deploy": "gh-pages -d build",
    "predeploy": "npm run build"

npm run deploy를 명령어로 치면 아래처럼 실행된다.

> react-for-beginners@0.1.0 predeploy
> npm run build


> react-for-beginners@0.1.0 build
> react-scripts build

Creating an optimized production build...
Compiled with warnings.

...

> react-for-beginners@0.1.0 deploy
> gh-pages -d build

Published

gh-pages -d buildbuild 파일을 https://{github-user-id}/github.io/{github-repository}에 업로드해준다.

완성된 웹 페이지는 여기서 확인 가능

profile
Make your lives Extraordinary!

0개의 댓글