구조분해 할당으로 prop 쉽게 가져오기

Apeachicetea·2021년 11월 16일
0

REACT 입문

목록 보기
9/9

구조분해 할당

객체

const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}

a, b, rest는 각각 어떤 값인가요?

a = 10, b = 20 , rest = {c:30, d: 40}

//App.js

import { useEffect, useState } from 'react';
import Movie from './Movie';

function App() {
  const [loading, setLoading] = useState(true);
  const [movies, setMovies] = useState([]);
  const getMoives = async() => {
    const json = await (
      await fetch("https://yts.mx/api/v2/list_movies.json?minimum_rating=9&sort_by=year")
      ).json();
    setMovies(json.data.movies);
    setLoading(false);
  }
  console.log(movies);
  useEffect(()=>{
    getMoives();
  }, [])

  return (
    <div> 
      {loading 
        ? <h1>Loading...</h1>
        : (<div>
            { movies.map(movie=> ( 
              <Movie medium_cover_image={movie.medium_cover_image} title={movie.title} summary={movie.summary} genres={movie.genres} />
            )
            )}
          </div>
          )}      
    </div>
  );
}

export default App;


//Movie.js

function Movie({ medium_cover_image, title, summary, genres }){
  return (
    <div>
      <img src={medium_cover_image} />
      <h2>{title}</h2>
      <p>{summary}</p>
      <ul>  
        {genres.map((genre, i)=><li key={i}>{genre}</li>)}
      </ul>
    </div>
  );
}

export default Movie;

결론

오른쪽 객체는 props이다. 구조분해 할당을 활용하면 medium_cover_image = movie.medium_cover_image이라는 결과를 얻을 수 있다.

{ medium_cover_image } = { medium_cover_image: movie.medium_cover_image }

profile
웹 프론트엔드 개발자

0개의 댓글