🔐 Archive/ReactJS

ReactJS로 웹서비스 만들기 3: State

YoungRock 2020. 3. 5. 15:57

Class component

  • 지난 시간 코드인 function component를 class component로 바꿨다.
  • class component에서는 return이 없고 render메소드에서 화면에 출력한다.
  • 또, class component를 쓰는 가장 큰 이유는 state라는 object가 있기 때문이다.

[코드]

import React from 'react';
import PropTypes from 'prop-types';

class App extends React.Component {

  state = {
    count: 0
  };

  add = () => {
    console.log("add");
  };

  minus = () => {
    console.log("minus");
  };

  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;

 

[실행 결과]

add를 누르면 add함수가, minus 를 누르면 minus함수가 실행된다.


State 값 바꾸기

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

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

위와 같이 했을 때 결과

count의 값이 바뀌지 않는다

  • state를 직접 변경하지 말라고 경고메세지가 뜬다.
  • 이렇게 하면 리액트가 render 함수를 refresh 하지 않기 때문

setState를 사용하여 값 변경

  • setState()를 실행할 때마다 리액트는 render를 rerender하기 때문에 값이 변경된다.
  add = () => {
    this.setState({count: 1});
  };

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

실행결과 add를 누루면 count가 1이되고, minus를 누르면 count가 -1이 된다.


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

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

를 하면 count 값이 1씩 증가, -1씩 감소하지만 위는 권장하지 않는 코드이다.

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

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

setState는 현재의 state값을 가져옴. 따라서 current.count는 현재 지금의 count 값을 말한다.


Component Life Cycle

  • component는 create되고 kill 되는 life cycle이 있다.
  • Mounting은 생성되는 것, unmounting은 죽는것, 즉 페이지가 바꿀때 등
  • 코드로 확인해보자

[코드]

import React from 'react';

class App extends React.Component {
  constructor(props){
    super(props);
    console.log("Hello. I'm constructor");
  }

  state = {
    count: 0
  };

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

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

  componentDidMount(){
    console.log("component rendered");
  }

  componentDidUpdate(){
    console.log("I just updated");
  }

  componentWillUnmount(){
    console.log("Goodbye")
  }

  render() {
    console.log("I'm rendering");
    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;

실행순서: 새로고침->Add->Add->Minus

[결과-console]

버튼을 누르면 update가 실행되고 render함수를 부른다.


example

import React from 'react';

class App extends React.Component {
  state = {
    isLoading: true,
    movie: []
  };

  componentDidMount(){
    setTimeout(() => {
      this.setState({isLoading: false});
    }, 6000);
  }

  render() {
    const { isLoading } = this.state;
  return <div>{isLoading ? "Loading" : "We are ready"}</div>;
  }
}

export default App;

실행결과: 6초 뒤에 isLoading을 false로 바꿈->6초뒤에 Loading이 we are ready로 바뀜