때때로 배우고, 설교하는 것을 실천하는 것이 옳지 않습니까?
Abstract
일반적인 React 클래스 라이프사이클 정리
공통적이고 더 중요한 항목만 나열됩니다:
- componentWillMount() 또는 UNSAFE_componentWillMount()는 버전 17 이상에서 더 이상 사용되지 않습니다.
- componentDidMount()
- componentWillUnmount()
- shouldComponentUpdate(), 성능 최적화의 핵심입니다.
- render()
밤을 예로 들어보겠습니다.
import { Component } from 'react'
interface Props {
 num: number
}
interface State {
 count: number
}
class Lifecycle extends Component {
 UNSAFE_componentWillMount(): void {
 /**
 * Called immediately before mounting occurs, and before Component#render. 
 * Avoid introducing any side-effects or subscriptions in this method.
 * This method will not stop working in React 17.
 */
 console.log('UNSAFE_componentWillMount()')
 }
 componentDidMount(): void {
 /**
 * Called immediately after a component is mounted.
 * Setting state here will trigger re-rendering.
 */
 console.log('componentDidMount()')
 }
 componentWillUnmount(): void {
 /**
 * Called immediately before a component is destroyed. 
 * Perform any necessary cleanup in this method, such as cancelled network requests, or cleaning up any DOM elements created in componentDidMount.
 */
 console.log('componentWillUnmount()')
 }
 shouldComponentUpdate(nextProps: Readonly<Props>, nextState: Readonly<State>, nextContext: any): boolean {
 /**
 * Called to determine whether the change in props and state should trigger a re-render.
 * Component always returns true. PureComponent implements a shallow comparison on props and state and returns true if any props or states have changed.
 * If false is returned, Component#render, componentWillUpdate and componentDidUpdate will not be called.
 */
 console.log('shouldComponentUpdate:', nextProps, nextState, nextContext)
 return this.props.num !== nextProps.num
 }
 render() {
 console.log('render()')
 return (
 <div>Lifecycle</div>
 )
 }
}
export default Lifecycle
초기화
출력 순서는 다음과 같습니다:
UNSAFE_componentWillMount()
render()
componentDidMount()
업데이트
부모 컴포넌트로부터 값을 수신하고 버튼을 클릭하여 이 값을 업데이트합니다. 출력 순서는 다음과 같습니다:
shouldComponentUpdate: {num: 2} null {}
render()
제거
상위 구성 요소에서 num 값을 늘리면 수명 주기 구성 요소가 제거됩니다.
{
 num < 3 && <Lifecycle num={num} />
}
출력 콘텐츠:
componentWillUnmount()
요약
- componentWillMount() 또는 UNSAFE_componentWillMount()를 호출해야 하며, 재사용을 권장하지 않습니다.
- 컴포넌트 초기화의 첫 번째 렌더링 렌더링() 후에 호출되는 componentDidMount()를 호출합니다.
- 컴포넌트가 제거되기 전에 호출되는 componentWillUnmount()는 일반적으로 리스너 취소, 타이머 지우기, 링크 닫기 등과 같은 정리 작업을 수행하는 데 사용됩니다.
- 성능 최적화의 핵심인 shouldComponentUpdate()는 컴포넌트의 리렌더링 필요 여부를 자율적으로 결정하여 추가적인 성능 손실을 줄일 수 있습니다. true 리렌더를 반환하고 그 반대의 경우 리렌더링을 하지 않습니다.



