#3 STATE

2021. 1. 10. 04:15·💻 Study/웹
728x90

3.0 Class Components and State

State

보통 우리가 동적 데이터와 함께 작업할 때 만들어진다.

변하는 데이터, 조재하지 않는 데이터

생겨나고선 사라지고 변경되는 데이터, 하나에서 2개 또는 0이 되는 그런 종류의 데이터들

 

-> state가 필요하다.

 

function component VS class component

function component

: function/ 무언가 return/ screen에 표시O

 

class component

: class/ react component로부터 확장/ screen에 표시O

- render method 내부에 넣어야만 ㅎ나다.

📌 react는 자동적으로 모든 class component의 render method를 실행한다.

- class compoent는 State를 가진다.

 

State

: object이다. component의 data를 넣을 공간이 있고 이 데이터는 변한다.

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

class App extends React.Component{
  state = {
    count: 0
  };
  // js code
  add = () => {
    console.log("add");
  };
  minus = () => {
    console.log("minus");
  }; 
  // end
  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버튼에 onClick발생 시, 이 클래스의 add function이 실행된다.


3.1 All you need to know about State

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

직접 state를 수정하면, react는 render function을 refresh하지 않는다.

Do not mutate state directly.

매번 state의 상태를 변경할 때는 react가 render function을 호출하여 바꿔주길 원한다.

 

setState function

: setState function호출 시, react는 view를 refresh원함을 알고, render function을 refresh한다.

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

  };

- Add와 Minus 버튼이 제대로 동작

BUT 위 코드도 좋은 형태는 아니다!

 

react는 똑똑하다.

현재 State를 가져오는 좋은 방법이 따로 있다!

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

  };

function의 형태로, current를 이용해 state의 count를 변경할 수 있게 된다.

 

📌 Everytime you call setState, react is going to rerender with the new state!

3.2 Component Life Cycle

life cycle method

: react가 component를 생성 그리고 없애는 방법

componentDidMount(){
    console.log("component rendered");
  }
  componentDidUpdate(){
    console.log("I just updated");
  }
  componentWillUnmount(){
    console.log("Goodbye, cruel world");
  }
  render(){
    console.log("I'm rendering");
    return <div></div>;
  }

Mounting

constructor(): js에서 class 생성할 때 사용되는 것

- component가 mount될 때, component가 screen에 표시될 때, component가 website에 갈 때, contructor를 호출한다.

- render 호출 이전에 호출됨

static getDerivedStateFromProps()

render()

componentDidMount() : 최초 Mount 됨을 알려줌/ render이후 실행

 

Updating

: 나에 의해 update가 발생

- component가 업데이트 될때, 호출되는function

- setState호출 시, component를 호출하고 먼저 render를 호출한 다음 update가 완료되었다고 하면, componentDidUpdate를 실행 

static getDerivedStateFromProps()

shouldComponentUpdate()

render()

getSnapshotBeforeUpdate()

componentDidUpdate()

 

UnMounting

component가 죽음을 의미

Page가 바뀔때

state를 사용하여 component 교체

다양한 방법이 있다.

componentWillUnmount(): component가 떠날 때 호출


3.4 Planning the Movie Component

더보기

📢

- javascript ternary operator (삼항연산자)
: Javascript이다. react아님!!

- timeout: Js꺼

import React from "react";

class App extends React.Component{
  state = {
    isLoading: true
  };
  componentDidMount(){
    setTimeout(() => {
      this.setState({isLoading: false}); 
    }, 6000);
  };
  render(){
    const { isLoading } = this.state; // state을 불러옴
    return <div>{isLoading ? "Loading..." : "We are ready"}</div>;
  }
}

export default App;

 

componentDidMount에서 data를 fetch 해보자!
API로부터 data fetching이 완료되면
"we are ready" 대신 movie를 Render하고 map을 만들고 movie를 render하도록!

 

Q. 내가 시작할 때 state에 뭔가 가지고 있는 데, book: true처럼 뭔가 추가하면 에러가 생길까?

A. NO! 에러가 발생하지 않는다.

import React from "react";

class App extends React.Component{
  state = {
    isLoading: true,
    movies: []
  };
  componentDidMount(){
    setTimeout(() => {
      this.setState({isLoading: false, book: true}); 
    }, 6000);
  };
  render(){
    const { isLoading } = this.state;
    return <div>{isLoading ? "Loading..." : "We are ready"}</div>;
  }
}

export default App;

- 미래에 쓰고자하는 처음부터 state를 선언하는 건 필수가 아니다. 

- state를 추가하는 건 자유다

- setState를 사용할 때 모든 default 값들을 선언할 필요는 없다.

 

🚩 다음 강의: react에서 data를 fetching하기!
728x90

'💻 Study > 웹' 카테고리의 다른 글

#5 CONCLUSIONS  (0) 2021.01.10
#4 MAKING THE MOVIE APP  (0) 2021.01.10
#2 JSX & PROPS  (0) 2021.01.10
#1 SETUP  (0) 2021.01.10
#0 INTRODUCTION  (0) 2021.01.10
'💻 Study/웹' 카테고리의 다른 글
  • #5 CONCLUSIONS
  • #4 MAKING THE MOVIE APP
  • #2 JSX & PROPS
  • #1 SETUP
soyang.
soyang.
코딩 및 개발 일지를 기록합니다.
  • soyang.
    소소한 코딩일지
    soyang.
  • 전체
    오늘
    어제
  • 링크

    • Github 🐾
    • 포트폴리오 📓 (리뉴얼중)
    • LinkedIn 👩🏻‍💼
  • 공지사항

    • 소소한 코딩일지
  • 블로그 메뉴

    • 방명록
    • 분류 전체보기 (181)
      • 🚩 목표 & 회고 (9)
      • 📓 Papers (10)
      • 🧇 Algorithm (44)
        • 이론 (1)
        • LeetCode (2)
        • 프로그래머스 (30)
        • 백준 (11)
      • 💻 Study (47)
        • 🤖 AI 인공지능 (3)
        • Python 파이썬 (3)
        • Docker 도커 (4)
        • 웹 (20)
        • 안드로이드 (2)
        • JAVA 자바 (1)
        • Firebase (3)
        • Linux 리눅스 (10)
      • 🍪 Projects (2)
      • 🎒 학교 (44)
        • 대학원 도비 (2)
        • 21 동계 모각코: 슈붕팥붕 (13)
        • 21 하계 모각코: 와팬호 (13)
        • 20 동계 모각코: 와팬호 (13)
      • 활동들 (16)
        • 인프런 대학생 LEAF 2기 (9)
        • 2021 Silicon Valley Online .. (7)
  • 태그

    error
    programmers
    React
    Linux
    Ai
    목표
    백준
    공부
    Algorithm
    리액트
    노마드코더
    알고리즘
    Python
    알고리즘스터디
    프로그래머스
    모각코
    Artificial Intelligence
    코딩테스트
    인프런대학생Leaf
    Gentoo
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
soyang.
#3 STATE
상단으로

티스토리툴바