[React] 화살표 함수 이용하기

김유진·2022년 8월 4일
0

React

목록 보기
24/64

리액트를 공부하면서 낯설었던 것 중의 하나가 바로 화살표 함수이다.
화살표 함수는 ES6에 처음 등장하였고, 함수를 보다 간략하게 선언할 수 있다는 강점이 있다.
화살표 함수는 callback 함수에서 this를 bind해야 한다는 문제도 발생하지 않는다. :)

callback 함수가 어떤 기능을 하고, 어떤 특징을 가지고 있는지 비교를 통해서 이해해보자.
함수를 호출할 수 있게끔 불러와보자!

class R013_ArrowFunction extends Component {
    constructor(props) {
        super(props);
        this.state = {
            arrowFuc : 'React200',
            num : 3
        };
    }
    componentDidMount(){
        Function1(1);
        this.Function2(1,1);
        this.Function3(1,3);
        this.Function4();
        this.Function5(0,2,3);
        function Function1(num1){
            return console.log(num1 +'. Es5 Function');
        }
    }
      ...

function1과 비교해보는데, function2를 화살표 함수로 작성해보자.


Function2 =( num1, num2 )=> {
       let num3 = num1+num2;
       console.log(num3 + '. Arrow Function : ' + this.state.arrowFunc);
   }

함수를 function 문자열 대신에 =>로 선언하였다! 함수 내에서 사용하는 thisR013_ArrowFunction 컴포넌트 그 자체를 의미한다. this로 컴포넌트의 state 변수에 접근하여 사용할 수 있다.

콜백 함수

콜백 함수 내부에서는 컴포넌트에 바로 this로 접근할 수 없기 때문에, 접근할 수 있는 변수에 this를 백업한다. 백업된 변수인 this_bind를 이용하여 컴포넌트의 state 변수에 접근할 수 있다.

 Function3 (){
        var this_bind = this;
        setTimeout(function() {
            console.log(this_bind.state.num + '.Es5 Callback Function noBind : ');
            console.log(this.state.arrowFunc);
        },100)
    }

console.log(this.state.arrowFunc)에서 콜백 함수 내부에서, this는 window 객체이기 때문에 this로 state변수에 접근하면, undefined 에러가 발생한다.

콜백 함수의 밖의 this를 bind해주면 this를 컴포넌트로 이용할 수 있다!

 Function4(){
        setTimeout(function() {
            console.log('4. Es5 Callback Function Bind : ' + this.state.arrowFuc);
        }.bind(this),100)
    }

그러나 화살표 함수에서는 this를 bind해주지 않아도, this를 컴포넌트로 사용하여 state변수에 접근 가능하다!

Function5 = (num1, num2, num3) => {
        const num4 = num1 + num2 + num3;
        setTimeout(() => {
            console.log(num4 + '.Arrow Callback Function :' + this.state.arrowFuc);
        },100);
    }

0개의 댓글