개발 R.I.P.

6.04 Dev.Feedback (React #1)

편행 2021. 6. 4. 15:16
반응형
class Habit extends Component {
    state = {
        count: 0,
    };

    handleIncrement = () => {
        // state 오브젝트 안에 있는 count를 증가 한뒤 state를 업데이트 한다
        this.setState({count: this.state.count + 1});
    };

    handleDecrement = () => {
        const count = this.state.count - 1;
        this.setState({count: count < 0 ? 0 : count });
    };


    render() {
    
    const {name, count} = this.props.habit;
    
        return (
        <li className = "habit">
        <span className="habit-name">Reading</span>
        <span className="habit-count">{this.state.count}</span>
        <button className = "habit-button habit-increase" 
        onClick = {this.handleIncrement}>
            <i className = "fas fa-plus-square"></i>
        </button>
        <button className = "habit-button habit-decrease"
        onClick = {this.handleDecrement}>
            <i className = "fas fa-minus-square"></i>
        </button>
        <button className = "habit-button habit-delete">
            <i className = "fas fa-trash"></i>
        </button>
        </li>
        )
    }
}

 

 

Class component에서는 초기 스테이트 값을 설정할 수 있는데, 그 state 는 객체이다.

state는 렌더 함수 이전에 작성을 해줘야 한다. 또한 state의 변화와 관련한 함수들 역시 render 함수 이전에 적어줘야 한다.

class Habit extends Component {
    state = {
        count: 0,
    };

    handleIncrement = () => {
        // state 오브젝트 안에 있는 count를 증가 한뒤 state를 업데이트 한다
        this.setState({count: this.state.count + 1});
    };

    handleDecrement = () => {
        const count = this.state.count - 1;
        this.setState({count: count < 0 ? 0 : count });
    };

render() {
blah blah
}

그럼 여기서 등장한 state란 무엇일까?

state & props

state의 개념을 정리하기 위해선 props라는 것과 같이 보는 것이 좋을 듯 하다.

react 공식 홈페이지에서 설명하는 state와 props의 차이점

 

props (“properties”의 줄임말) 와 state 는 일반 JavaScript 객체입니다. 두 객체 모두 렌더링 결과물에 영향을 주는 정보를 갖고 있는데, 방식에서 한 가지 중요한 차이가 있습니다. props는 (함수 매개변수처럼) 컴포넌트 전달되는 반면 state는 (함수 내에 선언된 변수처럼) 컴포넌트 안에서 관리됩니다.

 

State and Lifecycle – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

Components and Props – React

A JavaScript library for building user interfaces

ko.reactjs.org

Changing props and state ==> props와 state의 차이를 표로 정리한 것, 왼쪽이 props 오른쪽이 state

 

Can get initial value from parent Component?(초기값) Yes Yes
Can be changed by parent Component?(외부에서 접근) Yes No
Can set default values inside Component?*(초기값 설정) Yes Yes
Can change inside Component? (내부 설정) No Yes
Can set initial value for child Components? (???) Yes Yes
Can change in child Components? (외부에서 접근) Yes No

State is optional. Since state increases complexity and reduces predictability, a Component without state is preferable. Even though you clearly can't do without state in an interactive app, you should avoid having too many Stateful Components.

 

즉 props는 외부에서 들어온다. state는 내부에서만 작동된다. 라고 이해를 하고자 한다. 조금 더 디테일한 내용들이 정리가 되면, 바로바로 수정을 해야겠다.

그리고 글을 더 읽어보니 웬만하면 state를 사용하지 않는 것을 선호한다고 한다. 그 이유는 state가 componet를 복잡하게 만들어 결과 값을 예측하기 어렵게 만든다는 것. 물론 지금은 공부를 위해서 state를 사용하고 있지만, 계속 고민을 하여 props로만 각 컴포넌트들이 진행이 될 수 있게 만들어주는 것이 좋을 것 같다.

 

props에 대해서 한 번 더 짚고가자면,

props는 컴포넌트 밖에서 주어지는 데이터이다.

 

컴포넌트 안에서 자체적으로 데이터를 정의해서 사용하는 state와는 다르게, props는 컴포넌트 외부에서 데이터를 제공받는다.

이렇게 외부에서 데이터를 제공받게 하는 근본적인 이유는 컴포넌트의 재사용을 높이기 위해서이다. 상황에 따라 주어진 데이터를 받아 그 데이터에 맞게 UI를 보여주기 위해서 사용된다.

 

외부(상위) 컴포넌트에서 가져오기 위해 외부 컴포넌트 자체에서도 코드를 작성해주는데, 아래 코드에서 보는 것처럼

하위 컴포넌트의 내부에 변수를 설정해주고 외부(상위) 컴포넌트에서 설정한 객체를 전달해주기 위해 그 객체를 중괄호로 감싸서 넣어준다.

class Habits extends Component {
    state = {
        habits: [ 
            { id :1, name: 'Reading', count: 0},
            { id :2, name: 'Swimming', count: 0},
            { id :3, name: 'Coding', count: 0},
            { id :4, name: 'Home training', count: 0}
        ],
    };


    render() {
        return (
            <ul>
                {
                    this.state.habits.map(habit => (
                        <Habit key= {habit.id} habit = {habit}/>
                    ))}
            </ul>
        );
    }
}

props는 reder 함수 내부에서 값을 다룬다. 일반적으로 this.props를 이용하여 외부(상위) 컴포넌트의 값을 가져온다.

    render() {
    // 외부에서 들어오는 props의 값은 render 함수 내부에서 선언하여 다뤄줘야 한다.
        const {name , count} = this.props.habit

        return (
        <li className = "habit">
        <span className="habit-name">{name}</span>
        <span className="habit-count">{count}</span>
        <button className = "habit-button habit-increase" 
        onClick = {this.handleIncrement}>
            <i className = "fas fa-plus-square"></i>
        </button>
        <button className = "habit-button habit-decrease"
        onClick = {this.handleDecrement}>
            <i className = "fas fa-minus-square"></i>
        </button>
        <button className = "habit-button habit-delete">
            <i className = "fas fa-trash"></i>
        </button>
        </li>
        )
    }
}

 

이미 한 번 다뤄봤던 개념이지만, 다시 보니 또 새로운 것들이 보이고 그것에 이해가 부족하다는 것이 느껴진다.
계속 강의를 들어가며, 개념에 대해 하나하나 더욱 정확히 정리해가야한다.

 

반응형