[JS] 구조 분해 할당 (Destructuring assignment)

zhflsdl보보·2022년 11월 12일
0

JavaScript

목록 보기
7/10

구조 분해 할당이란, 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식이다.

배열

let users = ['Kim', 'Park', 'Lee'];
let [user1, user2, user3] = users;

console.log(user1) // 'Kim'
console.log(user2) // 'Park'
console.log(user3) // 'Lee'

해당하는 배열에 값이 없으면?

let [a, b, c] = [1, 2];
let [a=3, b=4, c=5] = [1,2];

console.log(a) // 1
console.log(b) // 2
console.log(c) // 5

값을 바꾸려면?

let a = 1;
let b = 2;

[a, b] = [b, a]

객체

let user = { name: 'Kim', age: 26};
let { name, age } = user;
// let name = user.name;
// let age = user.age;

console.log(name); // 'Kim'
console.log(age); // 26

ex1) 일반 함수

const user = {
  name: '김코드',
  age: '30',
  job: '프로그래머',
};

const getUserInfo = ({ name, age, job }) => {
  return `제 이름은 ${name}이고 나이는 ${age}살이며 ${job}입니다.`;
};

getUserInfo(user);

ex2) 컴포넌트 함수

// ProductList.js
const ProductList = () => {
  return (
    <ul>
    	{PRODUCT_LIST.map(product => {
     		<li key={product.id}>
    			<ProductItem product={product} />
	 		</li>
   		})};
	</ul>
   );
};

// ProductItem.js
const ProductItem = ({ product: { title, price, quantity } }) => {
  return (
    <>
      <span>{title}</span>
      <span>{price}</span>
      <span>{quantity}</span>
    </>
  );
};

ex3) 계산된 속성명을 이용한 input Handler 함수 합치기

input 태그의 name 속성명을 함께 이용하면 여러개의 인풋 핸들러를 하나로 합칠 수 있다. (name 속성은 오직 input 태그에서만 사용 가능!)

// Before
import React, { useState } from 'react';

const Login = () => {
  const [id, setId] = useState('');
  const [pw, setPw] = useState('');

  const saveUserId = event => {
      setId(event.target.value);
  };
  const saveUserPw = event => {
    setPw(event.target.value);
  };
  
  return (
    <div>
      <input type="text" onChange={handleEmail} />
      <input type="password" onChange={handlePassword} />
    </div>
  );
};

export default Login;


// After
import React, { useState } from 'react';

const Login = () => {
  const [userInfo, setUserInfo] = useState({id: '', pw: ''});
  
  const handleUserInfo = e => {
    const { name, value } = e.target;
    setUserInfo({...userInfo, [name]: value}); 
    // name은 key값, value는 value값. name은 id or pw 이므로 변하는 값이다. 
    // 그러나 컴퓨터 상에서 key값은 변하지 않는 값으로 알기 때문에 []로 감싸준다.
  };
    
  return (
    <div>
      <input type="text" onChange={handleUserInfo} />
      <input type="password" onChange={handleUserInfo} />
    </div>
  );
};

export default Login;
profile
매일매일 성장하는 개발자

0개의 댓글