본문 바로가기
{React}

10.13.22{코딩일기}벨로퍼트와 함께하는 모던리액트 1-24챕터리뷰

by Davey 2022. 10. 13.
728x90

[ 새롭게 알게된 것 ]


1. 클래스형 컴포넌트를 어쩔 수 없이 써야하는 경우는 3가지임


첫째. 클래스형 컴포넌트를 유지보수해야 할때

둘째. 옛날에 만들어진 리액트 라이브러리의 경우 Hooks이 지원 안될때(2가지 있다고함)

셋째. react-native관련 라우터 라이브러리 react-native-navigation를 사용해야 될때


 

2. 클래스형 컴포넌트 만드는 방법


기존에는 function Check({ name, phoneNumber, address}) { return (...) }

check.defaultProps = { name : 'bluevulepe' } 였다면 

클래스형 컴포넌트에는 render() 메서드가 반드시 필요함.

props를 조회할때는 this.props를 조회하면 됨.

class Hello extends Component {
  render() {
    const { color, name, isSpecial } = this.props;
    return (
      <div style={
      
      ...생략
      }
      </div>
     )
    }
   }

 


 

3. 클래스형 컴포넌트는 2가지 타입의 props 설정이 가능함


첫째. 함수형 컴포넌트와 동일한 방법으로 선언 가능

Hello.defaultProps = {
  name: '이름없음'
};

둘째. 클래스 내부에 static 키워드와 함께 선언 가능

class Hello extends Component {
  static defaultProps = {
    name: '이름없음'
  };
  render() {
  ...생략

 

4. 클래스형 컴포넌트안에 커스텀 메서드는 주로 'handle...'이라고 이름지음을 알게됨


클래스 내부에 종속된 함수를 '메서드'라고 칭함.

기존엔 const onIncrease = () => {  dispatch ( { type : 'INCREMENT'  } );  } ;  로 작성하던 방식이었음.

하지만 클래스 컴포넌트는 클래스 안에  아래와 같이 커스텀 메서드를 선언해줘야됨

import React, { Component } from 'react';

class Counter extends Component {
  handleIncrease() {
    console.log('increase');
  }

  handleDecrease() {
    console.log('decrease');
  }

  render() {
    return (
      <div>
        <h1>0</h1>
        <button onClick={this.handleIncrease}>+1</button>
        <button onClick={this.handleDecrease}>-1</button>
      </div>
    );
  }
}

export default Counter;

 


 

5.  4번예시의 this의 경우 Counter 클래스 컴포넌트를 가르키지 않는 오류 발생함


원인은 각 메서드와 컴포넌트 인스턴스의 관계가 특정 이벤트로 등록하는 과정에서 끊겨버리기때문임.


 

6.  클래스 컴포넌트와 메서드를 바인딩하는 방법 3가지


첫번째. constructor에서 bind 작업을 해주는 방법. (가장일반적인 방법)

class Counter extends Component {
  constructor(props) {
    super(props);
    this.handleIncrease = this.handleIncrease.bind(this);
    this.handleDecrease = this.handleDecrease.bind(this);
  }

두번째. 화살표 함수 문법을 사용해 커스텀 메서드를 선언하는 방법

이는 class-properties라는 문법을 사용하는데 정식 JS문법은 아님.

CRA(create-react-app)으로 만든 프로젝트엔 적용되는 문법이므로 이 방법을 가장 많이 사용함.

class Counter extends Component {
  handleIncrease = () => {
    console.log('increase');
    console.log(this);
  };

세번째. onClick에서 새로운 함수를 만들어 전달하는 것. (하지만 권장하지 않음.. 나중 렌더링할때마다 새로 함수생성됨)

return (
  <div>
    <h1>0</h1>
    <button onClick={() => this.handleIncrease()}>+1</button>
    <button onClick={() => this.handleDecrease()}>-1</button>
  </div>
);

 


 

 

7. 클래스형 컴포넌트에서 상태관리할때도 state를 사용함


단, state를 선언할때는 반드시 constructor 내부에서 this.state로 설정해주어야됨 반드시!

그리고 반드시 객체형태여야 render 메서드에서 this.state로 조회 가능해짐

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
  }

상태 업데이트 함수는this.setState 함수를 사용하면 됨

 handleIncrease = () => {
    this.setState({
      counter: this.state.counter + 1
    });
  };

 

8. class-properties문법을 메서드와 클래스를 바인딩에 사용했다면 constructor 없이도 상태관리 가능


참고로 7번의 경우 아래와 같이 대체해서 작성 가능함. 훨씬 간결해진 코드를 확일 할 수 있음.

class Counter extends Component {
  state = {
    counter: 0
  };
  handleIncrease = () => {
    console.log('increase');
    console.log(this);
  };
  render() {
    return (
      <div>
        <h1>{this.state.counter}</h1>
        <button onClick={this.handleIncrease}>+1</button>

 

9. setState도 함수형 업데이트 가능함.


함수형 업데이트는 보통 한 함수에 setState를 여러번에 걸쳐서 해야되는 경우 유용함.

만약 state.counter에 1을 더해주는 작업을 setState를 두번사용하면 2가 더해져야 될것 같지만 그렇게 안됨.

handleIncrease = () => {
  this.setState({
    counter: this.state.counter + 1
  });
  this.setState({
    counter: this.state.counter + 1
  });
};

하지만, 함수형 업데이트로 처리해주면 값이 2씩 잘 더해짐 확인가능함.

class Counter extends Component {
  state = {
    counter: 0,
    fixed: 1
  };
  handleIncrease = () => {
    this.setState(state => ({
      counter: state.counter + 1
    }));
    this.setState(state => ({
      counter: state.counter + 1
    }));
  };

이러한 현상의 원인은 setState를 한다고 해서 상태가 바로 바뀌는 게 아니기 때문.

성능적인 이유로 리액트에서는 상태를 바로 업데이트 시키지 않고 비동기적으로 업데이트함.


9. 동기적으로 어떤 작업을 하고 싶다면 setState의 두번째 파라미터에 콜백함수 넣어주면 됨


단순히 setState를 사용한다고 해서 상태가 바로 바뀌는게 아니기 때문에 적절한 때 콜백함수 넣어주면 좋음

 

  handleIncrease = () => {
    this.setState(
      {
        counter: this.state.counter + 1
      },
      () => {
        console.log(this.state.counter);
      }
    );
  };

 

728x90

댓글