상세 컨텐츠

본문 제목

클래스 컴포넌트에서 일반 함수와 화살표 함수의 차이점

Front-End/React

by devloper-jun 2024. 4. 21. 14:14

본문

 

 /* 클래스 컴포넌트에서 일반함수, 화살표 함수로 state 갱신 예제 */
 class Component extends React.Component {
 	constructor(props) {
    	super(props)
        this.state = {
        	counter: 0,
        }
    }
 
 
     functionCountUp() {
        console.log(this) // undefined
        this.setState((prevState) => ({counter: prevState.counter + 1}))
     }

     arrowFunctionCountUp = () => {
        console.log(this) // class Component
        this.setState((prevState) => ({counter: prevState.counter + 1})) 	
     }

     render() {
        return (
			<div>
            {/* cannot read properties of undefined reading 'setState' */}
            	<button onClick={this.functionCountUp}>functionCountUp</button>
            {/* 정상 작동 */}    
                <button onClick={this.arrowFunctionCountUp}>arrowFunctionCountUp</button>
            </div>
        )
     }
 }

- 일반 함수에서의 this는 undefined를 화살표 함수에서 this는 클래스 인스턴스인 this를 가리킴. 별도의 추가 작업 없이 this에 접근 가능하며 해당 차이점은 트랜스파일링으로도 확인 가능.

 

/* before transfile */
const arrowWorld = () => {
	console.log(this)
}

function world() {
	console.log(this)
}

/* after transfile */
var _this = void 0

var arrowWorld = function arrowWorld() {
	// 화살표 함수 내부의 _this 를 undefined로 변경 
	console.log(_this)
}

function world() {
	console.log(this)
}

- 화살표 함수는 this가 선언되는 시점에 이미 상위 스코프에 결정돼 _this를 받아서 사용하지만 일반함수를 런타임 시정에 this를 결정.

- 화살표 함수의 this는 선언 시점에 결정된다는 일반 함수와는 큰 차이점이 있으므로, this를 사용할 수 밖에 없는 클래스 컴포넌트에서는 각별한 주의가 필요!

'Front-End > React' 카테고리의 다른 글

자주 사용하는 Array prototype method  (2) 2024.09.26
React란? (1)  (0) 2023.11.30

관련글 더보기