react-js로 웹 서비스 만들기 3

·2020년 5월 19일
0

좌충우돌

목록 보기
4/26

3. state

(1) Class components and State

class component의 render method

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

class App extends React.Component{
    render(){
        return <h1>Im a class component1</h1>;
    }
}

export default App;

react는 자동적으로 App class component 내의 render method를 실행한다.

class component를 쓰는 이유: state

state는 데이터가 바뀌어도(하드 코딩하지 않고도) 데이터를 표시해 줄 수 있게 한다. 따라서 add, minus 버튼을 추가하고 동적으로 웹이 잘 동작할 수 있게 한다.
여기에서 state 객체의 구성 요소를 수정하기 위해서는 아래와 같이 두가지 방법을 쓸 수 있는데,
1. this.setState({count:this.state.count + 1});
2. this.setState((current) => ({ count: current.count + 1 }));
2번을 쓰라고 권장한다고 한다. 권장 이유는 찾아봐야 할 듯

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

class App extends React.Component {
    state = {
        count: 0,
    };
    add = () => {
        // setState: react updates the state and *calls the function render again with the new state*
        // 1.
        // this.setState({ count: this.state.count + 1 });
        // 1. case is bad because it shows ^this^ to the external side...?

        // 2.
        this.setState((current) => ({ count: current.count + 1 }));
    };
    minus = () => {
        this.setState((current) => ({ count: current.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;

결과화면:

(2) Component Life Cycle

constructor, render, mount, update, unmount

참고링크1;
참고링크2
1. constructor
constructor는 component가 생성될 때 호출되는 생성자
2. render
method that actual outputs HTML to the DOM
3. mount
mount는 component가 render된 이후에 일어나는 과정으로, "component를 DOM에 추가하는 과정"이다.
4. update
update는 DOM에 추가된 component에 변화를 주는 과정이다.

그래서 아래 코드와 같이 짜면

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

class App extends React.Component {
    constructor(props) {
        super(props);
        console.log("hello");
    }
    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 am 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;

1번은 처음 페이지 접속했을 때: constructor 불리고=>render() 불리고 =>mount
2번은 페이지 내의 add 버튼 눌렀을 때: render() 불리고=>update

profile
이것저것 개발하는 것 좋아하지만 서버 개발이 제일 좋더라구요..

0개의 댓글