๐ ๊ตฌ์กฐ ๋ถํด ํ ๋น(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 ...
}))
}
// 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 ...
}))
}
๋๊ธ