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

[ ๋ฆฌ์•กํŠธ(React) ] ํ•จ์ˆ˜๋กœ ์ „๋‹ฌํ•ด์ฃผ๋Š” ์ธ์ž๊ฐ€ 3๊ฐœ ์ด์ƒ์ผ ๋•Œ, ๊ฐ์ฒด๋กœ ๋ฌถ์–ด์„œ ์ „๋‹ฌํ•˜๊ธฐ

by YWTechIT 2021. 5. 16.
728x90

๐Ÿ“ ํ•จ์ˆ˜๋กœ ์ „๋‹ฌํ•ด์ฃผ๋Š” ์ธ์ž๊ฐ€ 3๊ฐœ ์ด์ƒ์ผ ๋•Œ, ๊ฐ์ฒด๋กœ ๋ฌถ์–ด์„œ ์ „๋‹ฌํ•˜๊ธฐ

ํ•จ์ˆ˜๋กœ ๋„˜๊ฒจ์ฃผ๋Š” ์ธ์ž๊ฐ€ 3๊ฐœ ์ด์ƒ์ด๋ฉด, ๊ฐ์ฒด ํ•˜๋‚˜๋กœ ๋ฌถ์–ด ๊ฐ€๋…์„ฑ์ด ์ข‹์•„์ง€๊ฒŒ๋” ํ•˜์ž. ๋‹ค์Œ ๋งํฌ๋Š” JS ํด๋ฆฐ ์ฝ”๋“œ ์ง€์นจ์„œ๋ฅผ ํ•œ๊ตญ๋ง๋กœ ๋ฒˆ์—ญํ•œ ๊นƒํ—ˆ๋ธŒ๋งํฌ์ด๋‹ค. ์–ด๋–ป๊ฒŒ ์ฝ”๋“œ๋ฅผ ์งœ์•ผํ• ์ง€ ๊ฐ์ด ์˜ค์ง€ ์•Š๋Š”๋‹ค๋ฉด ๋‹ค์Œ ๋งํฌ๋ฅผ ์ฐธ๊ณ ํ•˜์ž. Robert C. Martin's - Clean Code ํ•œ๊ธ€ ๋ฒˆ์—ญํŒ ํ•จ์ˆ˜(Functions)

 

์˜ˆ๋ฅผ ๋“ค์–ด, defaultScore ๊ฐ์ฒด์— str, dex, int, luck์˜ ๋Šฅ๋ ฅ์น˜๊ฐ€ ๋“ค์–ด์žˆ๋Š”๋ฐ ๋ฒ„ํŠผ์„ ํด๋ฆญ ํ•  ๋•Œ๋งˆ๋‹ค ๋Šฅ๋ ฅ์น˜๋ฅผ ์˜ฌ๋ผ๊ฐ€๊ฒŒ ์„ค์ •ํ•˜๋ ค๊ณ  ํ•œ๋‹ค๋ฉด, ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค. ์—ฌ๊ธฐ์„œ ์ค‘์š”ํ•œ ์ ์€ quizScore์—์„œ ์ธ์ž๋ฅผ ํ•˜๋‚˜ํ•˜๋‚˜ ๋”ฐ๋กœ ๋–ผ์–ด์„œ ๋ฐ›๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ ์ „์ฒด๋ฅผ ๋ฌถ์–ด์„œ ๋ณด๋‚ธ๋‹ค๋Š” ์ ์ด๋‹ค. ์ดํ›„์— ํ•จ์ˆ˜ ์•ˆ์—์„œ ๋ณ€์ˆ˜๋ฅผ ๋”ฐ๋กœ ์„ค์ •ํ•˜๋Š” ๊ณผ์ •์ด๋‹ค.

// src/pages/score/Constant.js
const defaultScore = {
  stats: {
    str: 0,
    dex: 0,
    int: 0,
    luck: 0,
  },
};

// src/components/App.js
const App = () => {
  const [score, setScore] = useState(defaultScore);

  const quizScore = (defaultScore) => {
    const str = defaultScore.stats.str;
    const dex = defaultScore.stats.dex;
    const int = defaultScore.stats.int;
    const luck = defaultScore.stats.luck;

    setScore = (score) => ({
      ...score,
      stat: {
        strScore: score.stats.str + str,
        dexScore: score.stat.dex + dex,
        intScore: score.stat.int + int,
        luckScore: score.stat.luck + luck,
      },
    });
  };
};
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€