연관 글
JS - this란?
리액트 클래스 컴포넌트는 state, props, 컴포넌트에 선언한 메서드 등을 참조하기 위해 this를 사용하고 있음을 직관적으로 확인할 수 있으며 따라서 코드를 작성할 때 this를 신경써야 합니다.
컴포넌트 안에서 this로 참조할 수 있는 프로퍼티
import React from "react";
class App extends React.Component {
// 컴포넌트 안 메서드 선언
componentMethod(){
console.log("method called !! method의 this는", this); //App 컴포넌트
};
componentDidMount() {
console.log('componentDidMount Called !! componentDidMount()의 this는', this); //App 컴포넌트
this.componentMethod(); // 메서드 호출
}
render() {
console.log('render Called !! render()의 this는', this); //App 컴포넌트
return (
<div>
<h1>Class Component this</h1>
</div>
);
}
}
export default App;
생명주기 메서드의 this는 메서드를 호출한 해당 컴포넌트를 가리킵니다.
따라서 컴포넌트안에 선언한 다른 메서드들도 생명주기 메서드 안에서 this로 호출 가능합니다.
JSX 이벤트 핸들러의 콜백 함수로 컴포넌트에서 선언한 메서드를 전달할 때 예외케이스가 발생합니다.
import React from "react";
class App extends React.Component {
// 상태값 num 선언
state = {
num: 0,
};
// 버튼을 누르면 this.state.num을 1만큼 증가시킴
increase() {
console.log('increase메서드의 this는', this);
this.setState((current) => ({ num: current.num + 1 }));
}
render() {
return (
<div>
<h2>{this.state.num}</h2>
{/* 클릭 이벤트 핸들러의 콜백으로 컴포넌트 메서드 전달 */}
<button onClick={this.increase}>증가</button>
</div>
);
}
}
export default App;
그 이유는 메서드가 실행될 때 바인딩된 this로 setState() 함수를 참조할 수 없기 때문인데, 이는 일반적으로 onClick={this.increase} 과 같이 뒤에 ()를 사용하지 않고 메서드를 참조할 경우 해당 메서드를 바인딩 해야하기 때문입니다.
해결방법 1. bind()
ex)
<button onClick={this.increase.bind(this)}>증가</button>
해결방법 2. 화살표 함수
ex)
<button onClick={() => this.increase()}>증가</button>
함수형 컴포넌트 자체와 함수형 컴포넌트 안에서 선언한 함수들 모두 전역 객체를 this로 가지고 있기 때문에 애초에 this가 모두 다 같습니다. 따라서 이벤트 핸들러에 콜백 함수를 넘기는 상황에도 신경 쓸 필요가 없습니다.