ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • React setState와 render
    Search: React React 2022. 11. 19. 06:57

     

    일반적 사용

    this.state.xxx에 값을 넣어 setState함수를 호출해 관리하면 redner가 자동 실행되도록 해야한다.

     

    render호출 예약 확인용 예제

    예제 코드

    class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {date: new Date()};
      }
    
      componentDidMount() {
        this.timerID = setInterval(
          () => this.tick(),
          1000
        );
      }
    
      componentWillUnmount() {
        clearInterval(this.timerID);
      }
    
      cnt = 0;
      tick() {
        this.cnt++;
        this.setState({
          //date: new Date()
        });
      }
    
      render() {
        return (
          <div>
            <h1>Hello, world!+{this.cnt}</h1>
          </div>
        );
      }
    }
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Clock />);

     

    실행화면, 초당 숫자가 올라가며 갱신된다.

     

    빈 setState함수를 호출해도 render가 자동 실행되어 갱신되면서 위의 cnt값이 화면에 갱신됨을 확인 할 수 있다.

     

    주의 setState호출 병합

    State 업데이트는 비동기적일 수도 있다.
    React는 성능을 위해 여러 setState() 호출을 단일 업데이트로 한꺼번에 처리할 수 있다.

     

    주의 render요청 병합

    setState()를 호출할 때 render가 1:1의 관계가 아니다.

     

    별도의 setState() 호출로 각 변수를 독립적으로 업데이트할 수 있다.

    fun1() {
        this.setState({
            val1: 11
          });
     }
    
     fun2() {
     	this.setState({
            val2: 22
          });
     }

    각각 변수들을 기록해두었다가 React 적당한 때 render가 호출된다.

     

    'React' 카테고리의 다른 글

    React props.children Ex  (0) 2022.11.19
    React Element 변수 Ex  (0) 2022.11.19
    React Event  (0) 2022.11.19
    생명주기 메서드 componentDidMount componentWillUnmount  (0) 2022.11.19
    React Counter 초당1씩 증가 예제  (0) 2022.11.19
    React Render  (0) 2022.11.19
    React State  (0) 2022.11.19
    React Element  (0) 2022.11.19

    댓글