TIL - State, life cycle

JS · 2020. 3. 2. 19:34

State and Lifecycle

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  ReactDOM.render(
    element,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

 

컴포넌트를 완전히 재사용하고 캡슐화하는 방법을 알아보자.

위의 코드를 캡슐화 하는것으로 시작한다.

 

function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

 

한 번만 코드를 작성하고 Clock이 스스로 업데이트하도록 만들려고 한다.

 

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

 

이것을 구현하기 위해서 Clock 컴포넌트에 "state"를 추가해야한다.

 

State는 props와 유사하지만, 비공개이며 컴포넌트에 의해 완전히 제어됩니다.

 


함수에서 클래스로 변환

 

1. React.Component를 확장하는 동일한 이름의 ES6.class를 생성

2. render()라고 불리는 빈 메서드를 추가

3. 함수의 내용을 render() 메서드 안으로 옮김

4. render() 내용 안에 있는 props를 this.props로 변경

5. 남아있는 빈 함수 선언을 삭제

 

class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

 

 

 

'JS' 카테고리의 다른 글

TIL - MYSQL 명령어  (0) 2020.03.23
TIL - Component, props  (0) 2020.03.02
Today I Learned - Inheritance Patterns  (0) 2020.02.14
Today I Learned - Time complexity  (0) 2020.02.14
Today I Learned - Tree, Binary Search Tree  (0) 2020.02.10