오늘의 공부
constructor 함수
- 클래스 컴포넌트에서 State를 사용하지 않아 State의 초기값 설정이 필요하지 않다면, 생성자 함수도 생략이 가능하다. 생성자 함수를 사용할 때는 반드시 super(props) 함수를 호출하여 부모 클래스의 생성자를 호출한다. 생성자 함수는 컴포넌트가 생성될 때 한 번만 호출된다.
ex class Counter extends React.Component<Props, State> { constructor (props: Props) { super(props); console.log('constructor'); this.state = { count : props.initValue, error : false, } }
render 함수
- 부모로부터 받은 Props 값이 변경되거나 this.setState로 State의 값이 변경되어 화면을 갱신할 필요가 있을 때마다 호출된다.
ex render() { console.log('render'); const {title} = this.props; const {count, error } = this.state; } . .
getDerivedStateFromProps 함수
- 부모로 부터 받은 Props와 State를 동기화 할 때 사용된다. 부모로부터 받은 Props로 State에 값을 설정하거나 Props에 의존하여 State값을 결정하고자 할때 사용한다.
ex) static getDerivedStateFromProps(nextProps: Props, prevState : State ) { console.log('getDerivedStateFromProps'); return null; }