본문 바로가기

■ 프로그래밍/React

State

전 글(2020/04/12 - Props)의 제일 하단에 완성된 코드를 보면 comment를 객체 형태로 선언한 것이 있다. 

이 것을 해당 컴포넌트의 state, 즉 컴포넌트의 상태 값을 의미한다. 

 

See the Pen Hello World in React by Dan Abramov (@gaearon) on CodePen.

 

Clock 컴포넌트를 통해, 스스로 타이머를 설정하고 매초 스스로 업데이트 하게 만들기 위해 함수형을 클래스형으로 바꾸겠다.

 

함수에서 클래스로 변환하기

1. React.Component를 확장하는 동일한 이름의 ES6 Class 생성 (ES6 Class는 추후 글 쓸 예정)

2. render() 메소드 추가

3. 함수의 내용을 render() { return ( 함수 내용 ); } 안에 작성

4. render() 안의 props를 this.props로 변경

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

1
2
3
4
5
6
7
8
9
10
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
cs

이렇게 완성되면 이제 Clock은 함수가 아닌 Class로 정의된다. 

 

클래스에 로컬 State 추가하기

1. render() 안의 this.props.datethis.state.date로 변경

1
2
3
4
5
6
7
8
9
10
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
cs

2. 초기 this.state를 지정하는 Class constructor(생성자 함수) 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
 
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
cs

클래스 컴포넌트는 항상 props로 기본 constructor를 호출하고, super(props)를 입력해야 한다. 

3. <Clock /> 요소에서 date prop 삭제

1
2
3
4
ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
cs

 

수정된 코드

See the Pen Hello World in React by Dan Abramov (@gaearon) on CodePen.

 

다음 글에서 Clock이 스스로 타이머를 설정하고 매초 스스로 업데이트 하도록 하겠다. 

이를 이해하려면 리액트의 생명주기에 대한 이해가 필요하다. 

'■ 프로그래밍 > React' 카테고리의 다른 글

Default Export, Named Export  (0) 2020.04.13
React Lifecycle(생명 주기)  (0) 2020.04.12
Props  (0) 2020.04.12
[React/에러] Module not found: Can't resolve './node_modules/react'  (0) 2020.04.12
Component(컴포넌트)  (0) 2020.04.11