State and Lifecycle[React]

SnowCat·2023년 1월 5일
0

React - Main Concepts

목록 보기
4/11
post-thumbnail

※ 공식문서를 읽고 정리한 글입니다.
Todo: 아래의 코드를 Hook없이 state를 사용해 리팩토링

const root = ReactDOM.createRoot(document.getElementById('root'));
  
function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  root.render(element);
}

setInterval(tick, 1000);

컴포넌트 변환

class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
  • 클래스형 컴포넌트를 만들 때에는 반환될 엘리먼트를 render() 메서드 안에 넣어주면 됨
  • 메서드를 선언할때 변수를 사용하지 않고 직접 선언함에 주의

State

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);
  • state 변수를 사용해 값의 변화를 화면에 표시해줄 수 있음
  • counstructor를 통해 this.state의 초기값을 지정해줄 수 있음
  • 예문에서 Clock이 렌더링될 때 state값이 h2태그에 출력됨

생명 주기 메서드

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);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);
  • componentDidMount, componentWillUnmount는 각각 DOM에 컴포넌트가 처음 렌더링될 때, DOM에서 컴포넌트가 삭제될 때 발생하는 메서드
  • 각각의 행동을 마운팅, 언마운팅이라고 하며, 컴포넌트가 마운트, 언마운트될 때 작동하는 메서드를 생명 주기 메서드라고 부름
  • 예문에서 componentDidMount()는 DOM이 렌더링 된 직후에 실행되어 타이머를 설정해주고, componentWillUnmount()는 DOM이 사라지기 직전에 타이머를 해제해주는 역할을 함
  • 상태 변화시 setState 메서드를 통해 hook없이 특정 값을 갱신해줄 수 있음

State 사용시 주의사항

this.state.comment = 'Hello'; // Wrong
this.setState({comment: 'Hello'}); // Correct
  • state를 직접 변경하면 컴포넌트는 렌더링되지 않음
// Wrong
// state와 prop의 업데이트는 비동기적일수 있음에 주의
this.setState({
  counter: this.state.counter + this.props.increment,
});

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));
  • 여러개의 setState() 호출을 하나로 합칠수는 있지만, this.props와 this.state의 업데이트는 비동기적일수 있음에 주의해야함
  componentDidMount() {
    fetchPosts().then(response => {
      this.setState({
        posts: response.posts
      });
    });

    fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
  }
  • state는 여러개의 변수를 포함할 수 있으며, 각각을 변경해도 다른 변수에 영향을 주지 않음
function FormattedDate(props) {
  return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}

class Clock extends React.Component {
  /*
  ...
  */
  render() {
    return (
      <div>
        <FormattedDate date={this.state.date} />
      </div>
    );
  }
}
  • state는 state를 소유하고 설정한 컴포넌트 이외의 다른 컴포넌트에서 접근할 수 없음
  • state는 자식 컴포넌트에 props로 값을 전달할수 있음
  • 따라서 state는 top-down 방식으로 데이터를 전달하는 것이 되며, 컴포넌트 트리에서 child에만 영향을 끼칠 수 있음

출처:
https://ko.reactjs.org/docs/state-and-lifecycle.html

profile
냐아아아아아아아아앙

0개의 댓글