WEB/ReactJS

React JS_State

yeommm 2020. 1. 20. 19:06

#3.0 ~ #3.3

아래 강의 중 'ReactJS로 웹 서비스 만들기'를 보고 배운 것과 모르는 것을 찾아 정리한 내용입니다.

https://academy.nomadcoders.co/courses

 

Academy

바닐라 JS로 크롬 앱 만들기 % Complete

academy.nomadcoders.co

 

 

1. Class Component

State를 다루기 위해서는 컴포넌트를 class component로 선언해야 한다. class component의 형식은 아래와 같으며, React.Component를 extends한다. React.Component안에 state(data)를 넣을 수 있고 변경이 가능하기 때문이다. 즉, State 데이터를 다루기 위해서는 react component를 확장한 class component로 선언해야 한다.

 

class component는 render method를 가지며, 리액트는 자동적으로 모든 class component의 render method를 실행한다. 따라서 아래 코드를 실행하면 브라우저에서 Hello를 볼 수 있다.

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

 

 

2. State

State는 동적인 데이터를 관리할 때 필요한 개념이다. props와 달리, component 내부에서 선언하여 변경할 수 있는 데이터 타입이다. state는 object이므로, 'this.state.변수명' 과 같은 형식으로 사용된다. 

 

state 값을 바꾸기 위해서는 setState 메서드를 사용해야 한다. state 값을 직접 바꾸기 위해 add 함수에서 'this.state.count: 1'라고 쓴다면 이는 제대로 동작하지 않는다. 리액트는 state의 상태가 변할 때 render function을 호출해서 바꾸기를 원하기 때문이다. 즉, state 값은 직접적으로 변경할 수 없고 항상 setState 메서드를 통해 변경해야 한다. 리액트에서는 setState가 호출될 때마다 새로운 state(변경된 state)와 함께 render function를 호출(리랜더링)하도록 설계되어 있다.

 

event에서 한 가지 주의해야 할 점은 함수를 전달할 때, onClick={this.add()}가 아닌, onClick={this.add}여야 한다는 것이다. 전자의 경우, 함수를 즉시 실행하라는 함수 호출이기 때문에 버튼을 클릭할 때마다 이벤트가 발생해야 한다는 의도와 맞지 않기 때문이다. 

//App.js
import React from 'react';
import PropTypes from "prop-types";

class App extends React.Component {
  state = {
    count: 0
  };
  
  add = () => {
    this.setState({count: this.state.count + 1});
  };

//setState를 할 때, 리액트에서 외부의 상태에 의존하지 않는 가장 좋은 방법
  minus = () => {
    this.setState(cur => ({count: cur.count - 1}));
  };

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

export default App;

 

 

3. Life Cycle

react component class는 단순히 render method 말고도 많은 메서드를 가지고 있다. 그 중 하나가 life cycle method이다. life cycle method는 component가 생성될 때, 사라질 때, 업데이트될 때 등 호출되는 몇 가지의 함수이다.

 

1. Mounting

Component가 생성될 때

- constructor(): component가 새로 만들어질 때 호출

- render(): component가 render될 때 호출

- componentDidMount(): component가 render됬을 때 호출

 

2. Updating

Component가 업데이트될 때

- render()

- componentDidUpdate(): 업데이트가 완료되었을 때 호출

 

3. Unmounting

Component가 사라질 때(페이지 바꿀 때)

- componentWillUnmount(): componet가 떠날 때 호출

 

 

 

#Reference

https://reactjs.org/docs/react-component.html