๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Frontend/React

[ ๋ฆฌ์•กํŠธ(React) ] ๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น(Destructuring Assignment)์œผ๋กœ ๊ฐ€๋…์„ฑ ๋†’์ด๊ธฐ

by YWTechIT 2021. 5. 25.
728x90

๐Ÿ“ ๊ตฌ์กฐ ๋ถ„ํ•ด ํ• ๋‹น(Destructuring Assignment)์œผ๋กœ ๊ฐ€๋…์„ฑ ๋†’์ด๊ธฐ

react์˜ ์ฝ”๋“œ๋ฅผ ๋ฆฌํŒฉํ† ๋งํ•˜๋˜ ์ค‘ handleClick ํ•จ์ˆ˜๋ฅผ moduleํ™” ์‹œ์ผœ๋†“๊ณ  handleClick์„ ์‚ฌ์šฉํ•ด์•ผํ•˜๋Š” ๊ฐ๊ฐ์˜ page์—์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„ ์–ธํ–ˆ์—ˆ๋‹ค.

 

categoryHandleClick์˜ combat, supply์˜ ๊ฒฝ์šฐ์— ๋ณ€์ˆ˜๊ฐ€ ๋งŽ์ง€ ์•Š์•„ ๊ทธ๋Ÿฌ๋ ค๋‹ˆ ํ•  ์ˆ˜ ์žˆ๊ฒ ์ง€๋งŒ, combatHandleClick, supplyHandleClick ๊ฐ™์€ ๊ฒฝ์šฐ ๋ณ€์ˆ˜๊ฐ€ 6๊ฐœ๋‚˜ ๋˜๊ธฐ ๋•Œ๋ฌธ์— ๊ดœํžˆ ์ฝ”๋“œ๊ฐ€ ๊ดœํžˆ ๊ธธ์–ด ๋ณด์ด๋Š” ๋“ฏํ•œ ๋Š๋‚Œ์„ ๋ฐ›์•˜๋‹ค. ์ด๋•Œ ๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น(Destructuring Assignment)์„ ์‚ฌ์šฉํ•˜๋ฉด ์ฝ”๋“œ๋ฅผ ๊น”๋”ํ•˜๊ฒŒ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. ๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น์ด ๋ฌด์—‡์ธ์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ๋‹ค๋ฉด ๋‹ค์Œ MDN๋ฌธ์„œ๋ฅผ ํ™•์ธํ•ด๋ณด์ž.

 

์ฒซ๋ฒˆ์งธ ์ฝ”๋“œ๋Š” ๊ตฌ์กฐ๋ถ„ํ•ดํ• ๋‹น ์ „ ์ฝ”๋“œ์ด๊ณ  ๋‘๋ฒˆ์งธ ์ฝ”๋“œ๋Š” ๊ตฌ์กฐ ๋ถ„ํ•ด ํ• ๋‹น ํ›„ ์ฝ”๋“œ์ด๋‹ค. ๋‘˜ ์ค‘ ์–ด๋–ค ์ฝ”๋“œ๊ฐ€ ๊ฐ€๋…์„ฑ์ด ๋” ๋†’์•„ ๋ณด์ด๋Š”๊ฐ€?! ์‚ฌ๋žŒ๋งˆ๋‹ค ๋‹ค๋ฅผ ์ˆ˜ ์žˆ๊ฒ ์ง€๋งŒ, ๋‚˜๋Š” ๋‘๋ฒˆ์งธ ์ฝ”๋“œ๊ฐ€ ๋” ๊ฐ€๋…์„ฑ์ด ์ข‹์•„ ๋ณด์ธ๋‹ค.

// Before Destructuring Assignment

// pages/category/index.js
const categoryHandleClick = (answer) => {
  const combat = answer.combat;
  const supply = answer.supply;

  setScore ((score) => ({
    ... skip code ...
  }))
}

// pages/combat/index.js
const combatHandleClick = (answer) => {
  const infantry = answer.infantry;
  const artillery = answer.artillery;
  const armor = answer.armor;
  const engineer = answer.engineer;
  const signal = answer.signal;
  const intelligence = answer.intelligence;

  setScore ((score) => ({
    ... skip code ...
  }))
}

// pages/supply/index.js
const supplyHandleClick = (answer) => {
  const affair = answer.affair;
  const medic = answer.medic;
  const weapon = answer.weapon;
  const police = answer.police;
  const pray = answer.pray;
  const band = answer.band;

  setScore ((score) => ({
    ... skip code ...
  }))
}
728x90
// after Destructuring Assignment

// pages/category/index.js
const categoryHandleClick = ({ combat, supply }) => {
  setScore ((score) => ({
    ... skip code ...
  }));
};

// pages/combat/index.js
const combatHandleClick = ({ infantry, artillery, armor, engineer, signal, intelligence }) => {
  setScore ((score) => ({
    ... skip code ...
  }))
}

// pages/supply/index.js
const supplyHandleClick = ({ affair, medic, weapon, police, pray, band }) => {
  setScore ((score) => ({
    ... skip code ...
  }))
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€