[react] 생명주기 메서드를 사용하여 상태 관리를 하려면 어떻게 해야 하나요?
1. componentDidMount
메서드를 활용하여 초기 상태 설정
componentDidMount() {
this.setState({ status: 'initialized' });
}
2. componentDidUpdate
메서드를 활용하여 상태 업데이트
componentDidUpdate(prevProps, prevState) {
if (this.props.data !== prevProps.data) {
this.setState({ data: this.props.data });
}
}
3. componentWillUnmount
메서드를 활용하여 정리 작업 수행
componentWillUnmount() {
// Clean up tasks, such as clearing intervals or cancelling API requests
}
위의 예시 코드에서 componentDidMount
, componentDidUpdate
, componentWillUnmount
메서드를 사용하여 상태 관리를 할 수 있습니다. 이러한 생명주기 메서드를 사용하여 컴포넌트의 상태를 관리할 수 있습니다. 상태가 변경될 때마다 원하는 작업을 수행할 수 있으므로 상태 관리에 유용하게 활용할 수 있습니다.
더 자세한 내용은 React 공식 문서를 참고하시기 바랍니다.