리액트 카운터 만들기

hhkim·2021년 7월 19일
0
post-thumbnail

🔗 react-counter 완성본


프로젝트 생성

  • npx create-react-app react-counter

Counter.js

간단한 앱이라서 따로 컴포넌트를 생성하지 않고 Counter.js에 모든 코드를 작성했다.

import React, { Component } from 'react';
import './Counter.css';

class Counter extends Component {
  state = {
    num: 0,
  };

  plus = () => {
    this.setState((state) => ({ num: state.num + 1 }));
  };

  minus = () => {
    this.setState((state) => ({ num: state.num - 1 }));
  };

  render() {
    return (
      <div className="counter">
        <div className="counter-box">
          <h1 className="title">Let's count!</h1>
          <div className="num">{this.state.num}</div>
          <div className="buttons">
            <button onClick={this.plus}>+</button>
            <button onClick={this.minus}>-</button>
          </div>
        </div>
      </div>
    );
  }
}

export default Counter;
  • state에 필요한 값은 현재 숫자인 num
  • +와 - 버튼을 눌렀을 때 호출할 plusminus 이벤트 핸들러 작성 및 이벤트 리스너 설정

❓ 이벤트 핸들러를 화살표 함수로 작성한 이유

참고

  • 이벤트 핸들러를 리스너에 설정하면서 새로운 함수가 생성되어 this.setState()undefined가 된다.
  • 따라서 컴포넌트와 이벤트 핸들러를 바인딩하여 this를 사용할 수 있도록 해야하는데, 화살표 함수를 사용하면 자동으로 바인딩을 해준다.

this.setState()에 함수를 전달한 이유

참고

  • this.state는 렌더링된 값을 갖는다.
  • this.setState()는 비동기적이며 일괄적으로 처리된다.
incrementCount() {
  this.setState({count: this.state.count + 1});
}
handleSomething() {
  // `this.state.count`가 0에서 시작한다고 해봅시다.
  this.incrementCount();
  this.incrementCount();
  this.incrementCount();
  // React가 컴포넌트를 리렌더링할 때 `this.state.count`는 3이 될 것 같은 예상과 달리 1이 됩니다.
  // 이것은 `incrementCount()` 함수가 `this.state.count`에서 값을 읽어 오는데
  // React는 컴포넌트가 리렌더링될 때까지 `this.state.count`를 갱신하지 않기 때문입니다.
  // 그러므로 `incrementCount()`는 매번 `this.state.count`의 값을 0으로 읽은 뒤에 이 값을 1로 설정합니다.
}

👉 핸들러에서 this.state.num 값을 바로 변경하는 경우 원치 않는 값으로 변경될 수 있다.

incrementCount() {
  this.setState((state) => {
    // 중요: 값을 업데이트할 때 `this.state` 대신 `state` 값을 읽어옵니다.
    return {count: state.count + 1}
  });
}
handleSomething() {
  // `this.state.count`가 0에서 시작한다고 해봅시다.
  this.incrementCount();
  this.incrementCount();
  this.incrementCount();
  // 지금 `this.state.count` 값을 읽어 보면 이 값은 여전히 0일 것입니다.
  // 하지만 React가 컴포넌트를 리렌더링하게 되면 이 값은 3이 됩니다.
}

👉 정확한 값을 전달하기 위해 이렇게 코드를 작성하는 습관을 들이는 것이 좋다!


깃헙 페이지에 배포

  • gh-pages 설치
    npm i gh-pages

package.json

  • homepage 추가
    "homepage": "https://[사용자명].github.io/[프로젝트명]"
  • scripts에 deploy, predeploy 추가
    프로젝트를 build하면 build 폴더가 생성됨
 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "deploy": "gh-pages -d build",
    "predeploy": "npm run build"	// deploy 명령을 하면 자동으로 실행됨
},
  • npm run deploy로 배포

0개의 댓글