혼자 공부하면서 정리한 글입니다. 오류가 있다면 알려주시길 바랍니다 🙇🏻
lifecycle method
)getDerivedStateFromProps
, render
, componentDidMount
getDerivedStateFromPreops
(props 변경시), shouldComponentUpage
, render
, getSnapshotBeforeUpate
, compoenetDidUpdate
setState
나 forceUpate
메서드가 컴포넌트 내에서 호출될 때props
가 컴포넌트로 전달되 때componentWillUnmount
static getDerivedStateFromProps
메서드getDerivedStateFromProps
는 static 클래스 메서드로 컴포넌트가 생성될 때와 컴포넌트가 새 props
를 전달받을 때 모두 호출된다.
새로운 props
와 가장 최근의 state
를 인수로 전달받아서 하나의 객체를 반환한다.
객체의 데이터는 컴포넌트의 state
로 갱신된다.
Derived는 파생이란 뜻
export default class App extends Component {
state = {
userLoggedIn: false
}
static getDerivedStateFromProps(nextProps, nextState) {
if (nextProps.user.authenticated) {
return {
userLoggedIn : true
}
}
return null
}
render() {
return (
<View>
{
this.state.userLoggedIn && (
<AuthenticatedComponent />
)
}
</View>
);
}
}
componentDidMount
생명주기 메서드componentDidMount
는 컴포넌트가 로딩되고서 바로 한 번만 호출된다.
Ajax 호출로 가져온 데이터를 처리하거나, 지정된 실행 후에 실행되는 setTimeout
처리를 하거나, 다른 자바스크립트 프레임 워크들과 통합하기에 적절한 위치이다.
class MainComponent extends Component {
constuctor() {
super()
this.state = { loading: true, data: {} }
}
conponentDidMount() {
#simulate ajax call // Ajax 호출을 한다면
setTimeout(() => {
this.setState({
loading: false,
data: {name: '리액트 네이티브', age: 30}
})
}, 2000)
}
render() {
if(this.state.loading) {
return <Text>Loading</Text>
}
const { name, age } = this.state.data
return (
<View>
<Text>이름: {name}</Text>
<Text>나이: {age}</Text>
</View>
)
}
}
shouldComponentUpate
생명주기 메서드shouldComponentUpate
메서드는 Boolean을 반환하며 컴포넌트의 랜더링을 할 것인지 결정할 수 있다.
새로운 state
나 props
가 컴포넌트나 자식 컴포넌트의 랜더링이 필요하지 않다고 판단되면 false
를 반환한다.
컴포넌트를 다시 랜더링하고 싶다면 true
를 반환한다
class MainComponent extends Component {
shouldComponentUpdate(nextProps, nextState) {
if(nextProps.name !== this.props.name) {
return true // 랜더링 함
}
return false // 랜더링 안함
}
render() {
return <SomeComponent />
}
}
componentWillUnmount
생명주기 메서드componentWillUnmount
메서드는 앱에서 컴포넌트가 파기되기 전에 호출된다.
componentDidMount
메서드에서 설정된 필요한 정리를 하고 리스너를 삭제하고, 타이머를 제거하도록 지정할 수 있다.
class MainComponent extends Component {
handleClick() {
this._timeout = setTimeout(() => {
this.openWidget();
}, 2000);
}
componentWillUnmount() {
clearTimeout(this._timeout);
}
render() {
return <SomeComponent
handleClick={() => this.handleClick() }/>
}
}
함수형 컴포넌트에 익숙해서 뭔가 이런 메서드들이 낯설다;;