[React] Day 3

이찬형·2020년 2월 26일
0

reactMovieApp

목록 보기
3/5
post-thumbnail

Day 3


저번엔 정적인 값을 넘기기 위해 props를 사용했습니다.
만약 버튼을 눌렀을 때 카운트가 올라가는 기능을 구현하려면 어떻게 해야 할까요??

동적인 값을 다룰 때에는 state를 사용합니다. state는 class형 컴포넌트에서 선언할 수 있어요.

class형 컴포넌트는 어떻게 선언하는지, state는 어떻게 다루는지 직접 코딩해봐요!!

class형 컴포넌트

함수형 컴포넌트는 아래와 같이 선언했습니다.

function App() {
  return <h1>Hello!</h1>;
}

이걸 클래스형 컴포넌트로 바꿔볼게요.

class App extends React.Component {
  render() {
    return <h1>Hello!</h1>;
  }
}

render() 메소드 안에 리턴값으로 준 것을 HTML로 뿌려줘요.

state

state는 하나의 객체입니다. 클래스 컴포넌트 안 쪽에 선언해주면 돼요.

class App extends React.Component {
  state = {
    count: 0
  };
  
  render() {
    return <h1>Count: {this.state.count}</h1>;
  }
}

state 내부에 있는 값을 바꾸기 위해선 setState() 메소드를 사용해야 합니다.
직접적인 참조는 에러를 던져주면서 바뀌지 않아요!!

class App extends React.Component {
  state = {
    count: 0
  };

  add = () => {
    this.setState({ count: this.state.count + 1 });
  };

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

  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    );
  }
}

this.state의 반복을 피하기 위해 아래와 같이도 선언 가능합니다.

class App extends React.Component {
  state = {
    count: 0
  };

  add = () => {
    this.setState(current => current.count++);
  };

  minus = () => {
    this.setState(current => ({ count: current.count - 1 }));
  };

  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    );
  }
}

add()minus()화살표 함수 형태로 선언하지 않으면 버튼 클릭 이벤트 발생 시 this와의 연결이 끊겨요.

따라서 생성자에서 bind() 해줄 필요가 있습니다.

Life Cycle

컴포넌트가 처음 렌더링되고, 업데이트되고, 사라지는 것을 라이프사이클이라고 해요.

  • ComponentDidMount()는 컴포넌트가 처음 렌더링됐을 때 호출됩니다.
  • ComponentDidUpdate()는 state가 업데이트 되었을 때 호출됩니다.
  • ComponentWillUnmount()는 컴포넌트 소멸 시 호출됩니다.
class App extends React.Component {
  state = {
    count: 0
  };

  add = () => {
    this.setState(current => current.count++);
  };

  minus = () => {
    this.setState(current => ({ count: current.count - 1 }));
  };

  componentDidMount() {
    console.log("Rendered!!");
  }

  componentDidUpdate() {
    console.log("Updated!!");
  }

  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    );
  }
}

페이지를 불러올 때 App 컴포넌트를 불러오면서 "Rendered!!"가 찍히고, 버튼을 클릭할 때마다 "Updated!!"가 찍힙니다.

마무리

아직 정리가 덜 된 부분이 있어서 계속 공부하면서 작성하겠습니다.

감사합니다 :D

profile
WEB / Security

0개의 댓글