구조분해할당

Hyemimi·2022년 6월 23일
0

React

목록 보기
2/17
  1. 객체

me 라는 객체의 key 값을 중괄호에 적어주면 각각
name, age, height라는 이름의 변수에 객체의 value가 할당됨



const me = {name : "이혜미", 
            age : 22,
           height : 162}

const {name, age, height} = me; 
cosole.log(name,age,height); // output : 이혜미 22 162

객체의 key를 변수명으로 하고 싶지 않을 때는
const { (객체의 key) : (바꾸고 싶은 이름) } = (객체의 이름) 으로 선언함


const {name : my_name, age : my_age,
   height : my_height} = me;
console.log(my_name,my_age,my_height); 
// output : 이혜미 22 162
  1. 배열
const me = ["이혜미", 22, 162]; // 배열 선언
const [name,age,height] = me;
console.log(name,age,height) // output : 이혜미 22 162

props

props는 객체 형태로 전달

[App.js]


import Profile from "./profile";

export default function App() {
  const me = ["이혜미", 22, 162];
  const [me_name, me_age, me_height] = me; 
  // 배열 구조분해할당
  
  return (
    <div>
      <Profile name={me_name} 
age={me_age} height={me_height} />
    </div>
  );
}

[profile.js] : props X

function Profile({ name, age, height }) {
  console.log(name, age, height); 
  // output : 이혜미 22 162
}

export default Profile;

[profile.js] : props O

function Profile(props) {
  console.log(props.name, props.age, props.height);
  // output : 이혜미 22 162
}

export default Profile;

defaultProps로 미리 기본값 설정, 오류 예방

위의 App.js에서 할당해준 height = {me_height}를 지우면, profile.js의 height에는 undefined 값이 자동으로 남게 된다.
이를 방지하기 위해 기본값을 설정한다.

<컴포넌트 외부에서 설정>

컴포넌트명.defaultProps = {}

[Profile.js]

function Profile({ name, age, height }) {
  console.log(name, age, height); 
  // output : 이혜미 22 170
}

Profile.defaultProps = {
  height: 170 
  // height에는 undefined가 아닌 기본값 165
};
export default Profile;

[App.js]

import Profile from "./profile";

export default function App() {
  const me = ["이혜미", 22, 162];
  const [me_name, me_age, me_height] = me;
  return (
    <div>
      <Profile name={me_name} age={me_age} />
    //height는 할당되지 않음, 기본값
    </div>
  );
}
profile
암냠냠

0개의 댓글