클래스 컴포넌트의 this는 불변값이 아니다.
class ProfilePage extends React.Component {
showMessage = () => {
alert('Followed ' + this.props.user);
};
handleClick = () => {
setTimeout(this.showMessage, 3000);
};
render() {
return <button onClick={this.handleClick}>Follow</button>;
}
}
function ProfilePage(props) {
const showMessage = () => {
alert('Followed ' + props.user);
};
const handleClick = () => {
setTimeout(showMessage, 3000);
};
return (
<button onClick={handleClick}>Follow</button>
);
}
리액트에서 props는 불변값(immutable)이라 함수형 컴포넌트의 props는 고정된다.
요청이 진행되고 있는 상황에서 클래스 컴포넌트가 다시 렌더링 된다면, this.props는 바뀐다.
해결책
class ProfilePage extends React.Component {
showMessage = (user) => {
alert('Followed ' + user);
};
handleClick = () => {
const {user} = this.props;
setTimeout(() => this.showMessage(user), 3000);
};
render() {
return <button onClick={this.handleClick}>Follow</button>;
}
}
→ 하지만, 코드의 복잡성이 증가하며 버그가 생기기 쉬운 구조가 된다.
class ProfilePage extends React.Component {
render() {
// props의 값을 고정!
const props = this.props;
// Note: 여긴 *render 안에* 존재하는 곳이다!
// 클래스의 메서드가 아닌 render의 메서드
const showMessage = () => {
alert('Followed ' + props.user);
};
const handleClick = () => {
setTimeout(showMessage, 3000);
};
return <button onClick={handleClick}>Follow</button>;
}
}
함수형 컴포넌트에서 특정 render에 종속되지 않은 가장 최근의 state나 props를 읽는 방법(나중에 render될 값을 미리 가져와서 쓰려면?)
unction MessageThread() {
const [message, setMessage] = useState('');
// 최신값을 쫓아간다
const latestMessage = useRef('');
useEffect(() => {
latestMessage.current = message;
});
const showMessage = () => {
alert('You said: ' + latestMessage.current);
};
To-Do: 라이프 사이클 조사