React, State

00_8_3·2020년 9월 20일
0

리액트에서 State란

리액트에도 생명주기가 있다.

마운트
contructor()
render()
componentDidMount()

업데이트
render()
componentDidUpdate()

마운트 해제
componentWillUnmount()

class ErrorBoundary extends React.Component {
  constructor(props) {
  		//컴포넌트를 만들 때마다 호출되는 클래스 생성자 메서드
		//안에 this.state 초기값 설정
		//내부에서는 setState 호출하면 안된다.
    super(props);
    this.state = { counter: 0 };
	this.handleClick = this.handleClick.bind(this);
  }
	componentDidMount{
		//컴포넌트가 마운트된 직후 호출된다.
		//
		
		this.setState((state, props)=>{
			return ;
		});
			//state : updater , props: 콜백함수
	}
	componentDidUpdate(props){
		//갱신이 일어난 직후 호출된다.
		//setState를 즉시 호출가능하다 (되도록 조건문사용)
		
		
	}
	
	componentWillUnmount(props){
		//해제되기 직전에 호출된다.
		//
		//컴포넌트가 다시 렌더링 되지 않으므로 
		//내에서 setState를 호출하지 않는다.
	}

  render() {
  	//UI를 렌더링 하는 메서드
	//DOM을 렌더링
    
    return this.props.children;
  }
}
  1. constructor의 state가 초기화 된다

  2. render()된다.

  3. componentDidMount() 가 호출된다. 호출된 것 안의 메서드가 호출된다.

  4. 호출된 메서드로인해 setState가 호출되서 갱신이된다.

  5. 갱신을 감지한 브라우저가 render을 다시 호출한다.

  6. 이때 render 안의 this.state가 달라지고 출렵값이 업데이트 된다.

  7. 컴포넌트가 DOM으로부터 한번이라도 삭제된적이 있으면 componentWillUnmount를 호출한다.

useState와 useEffect 훅을 사용하여 간단히 사용 가능하다.

0개의 댓글