본문 바로가기
웹 프로그래밍 기초/자바기반의 웹&앱 응용SW 개발자

자바기반의 웹&앱 응용 SW개발자 양성과정 78일차 -116

by oncerun 2020. 7. 9.
반응형

 

React State 

<div id="root"></div>

 

 

//하나의 시계
class Clock extends React.Component{
  
  // <Clock />이 render로 전달되었을때 생성자가호출됨
  constructor(props){
    super(props);
    this.state = {date : new Date()};
  }
  
  //DOM의 출력값이 삽입되면(렌더링되면)호출됨  
  componentDidMount(){
    this.timerID = setInterval( //브라우저가 요청
      ()=> this.tick(),1000
    )
  }
  
  componentWillUnmount(){
    clearInterval(this.timerId);
  }
  
  //요청받아 현재 시각을 포함하는 객체를 호출하여 UI를 업데이트
  tick(){
    this.setState({ //호출로써 React는 state가 변경된것을 인지하며 render()재호출
      date : new Date()
    });
    
  }
  //2번째로 호출되어 렌더링됨
  render(){
 //렌더링의 출력값을 일치시키기위해 DOM업데이트를함.
    return (
    
     <div>
        <h1> Time</h1>
        <h2> time is {this.state.date.toLocaleTimeString()}</h2>
     </div>
   );
  }
}


//Clock 컴포넌트가 DOM으로 부터 한번이라도 삭제된 적이 있다면 componentWillmount() 생명 주기 메서드를 호출


    
  ReactDOM.render(
    <Clock/>,
    document.getElementById('root')             
     );  

 

 

State 올바르게 사용하기

 

직접 state를 수정하면 안 된다. 

//wrong
this.state.comment = 'hello';

//correct
this.setState({comment : 'hello'});

그럼 컴포넌트는 state의 update를 인식하지 못합니다.

대신 우리는 setState()메소드를 사용합니다.

 

 

state 업데이트는 비동기적일 수도 있습니다.

 

 

다음과 같은 코드는 업데이트에 실패할 수 있습니다.

this.setState({
	counter : this.state.couter + this.props.increment,
    });

이를 수정하기위해 객체보다는 함수를 인자로 사용하는 다른 형태의 setState()를 사용합니다.

이전 state를 인자로 받아들이며 업데이트가 적용된 시점의 props를 두 번째 인자로 받아들일 것입니다.

this.setState((state, props)=>({
	counter : state.counter + props.increment
}));

 

top-down 방식, 데이터 흐름이라고 합니다.

모든 state는 항상 특정한 컴포넌트가 소유하고 있으며 그 state로부터 파생된 UI 또는 데이터는 오직 트리구조에서 자신의 아래에 있는 컴포넌트에만 영향을 미칩니다.

반응형

댓글