PaulMuadDibUsul / react-group-study

0 stars 5 forks source link

07 스터디 퀴즈 [리액트의 라이프 사이클 메서드] #23

Open EYEG opened 6 months ago

EYEG commented 6 months ago

다음 라이프사이클 메서드들을 일반적인 실행 순서대로 나열해보기

EYEG commented 6 months ago
cheesepizza453 commented 6 months ago

state나 props 변경했을 때, 리렌더링을 시작할지 여부를 지정하는 메서드는 무엇일까요?

  1. componentDidMount 메서드
  2. shouldComponentUpdate 메서드
  3. getSnapshotBeforeUpdate 메서드
  4. componentDidUpdate 메서드
ohr0226 commented 6 months ago
스크린샷 2024-02-06 오후 11 36 45

라이프사이클이 두 번씩 호출되는 이유는?

ohr0226 commented 6 months ago
  1. 컴포넌트가 업데이트 되는 경우 4가지 설명해보기

  2. 업데이트 라이프사이클 나열하기

    • shouldComponentUpdate
    • render
    • componentDidUpdate
    • getDerivedStateFromProps
    • getSnapshotBeforeUpdate
andrewylies commented 6 months ago

다음 내용이 설명하는 라이프사이클 메서드는?

  • 컴포넌트를 만들고, 첫 렌더링을 다 마친 후 실행된다.
  • 이 메서드에서 다른 자바스크립트 라이브러리 또는 프레임워크의 함수를 호출하거나 이벤트 등록, setTimeout, setInterval, 네트워크 요청과 같은 비동기 작업을 처리하면 된다.
seokhj commented 6 months ago
class ColorBox extends Component {
    state = {
        color: 'black'
    };

    componentDidMount() {
        console.log('실행');
        setTimeout(() => {
            this.setState({
                color: 'red'
            })
        },2000);
    }

    getSnapshotBeforeUpdate(prevProps, prevState) {
        console.log("getSnapshotBeforeUpdate");
        if (prevProps.color !== this.props.color) {
            return this.myRef.style.color;
        }
        return null;
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        console.log(snapshot)
        console.log("componentDidUpdate", prevProps, prevState);
        if (snapshot) {
            console.log(snapshot);  // <1번문제>
        }
    }

    render() {

        return(
            <div style={{color:this.state.color}}>2번 문제</div>
        );
    };

}

export default ColorBox;

1) 위 코드에서 "1번문제" 결과값과, "2번문제"에서 나타나는 현상은 무엇일까요? 2) 만약 componentDidUpdate 메서드를 삭제하면 어떤 결과가 나올까요?

정답

1) 1번문제 : 이전 색상값 / 2번문제 : 글자색상이 2초 뒤, 검정색에서 빨간색으로 바뀐다.

참고

2) getSnapshotBeforeUpdate() 메서드는 componentDidUpdate() 3번째 파라미터값에 꽂혀야 호출되기 때문에 콘솔에 "getSnapshotBeforeUpdate() should be used with componentDidUpdate"라고 에러가 뜬다.