[react] 생명주기 메서드를 사용하여 컴포넌트 간 데이터 전달을 관리하는 방법은 무엇인가요?
componentDidMount
메서드는 컴포넌트가 생성된 후 호출되며, 초기화된 데이터를 가져와서 상태(State)를 업데이트 하는 데 유용합니다.
import React, { Component } from 'react';
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
// 데이터를 가져와서 상태를 업데이트
// 예: API 호출
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
return <ChildComponent data={this.state.data} />;
}
}
componentDidUpdate
메서드는 컴포넌트의 업데이트가 발생한 후 호출되며, 데이터의 변경에 대응하여 추가적인 작업을 수행할 수 있습니다.
import React, { Component } from 'react';
class ChildComponent extends Component {
componentDidUpdate(prevProps) {
// 이전 데이터와 현재 데이터를 비교하여 필요한 작업 수행
if (this.props.data !== prevProps.data) {
// 데이터가 업데이트되었을 때 처리
}
}
render() {
// 컴포넌트 렌더링
}
}
이러한 생명주기 메서드를 통해 컴포넌트 간에 데이터를 효과적으로 전달하고 관리할 수 있습니다.