새소식

🍪 Study/웹

#3 STATE

  • -
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
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.