리액트 공식문서 스터디 3일차

hyebin Jo·2022년 7월 21일
0

5. State와 생명주기

함수에서 클래스로 변환

//함수형
function Clock(props) {
  return <div>{props.date.toLocaleTimeString()}</div>;
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}
//클래스형
class Clock extends React.Component {
  render() { //render() 메서드 추가
    return <div>{this.props.date.toLocaleTimeString()}</div>;
  } //props를 this.props로 변경
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}

클래스에 로컬 State 추가하기

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  } //초기 this.state를 지정하는 class constructor를 추가
  
  render() { 
    return <div>Hello, {this.state.date.toLocaleTimeString()}!</div>;
  } //this.props.date를 this.state.date로 변경
}

ReactDOM.render(
  <Clock />, //Clock컴포넌트에 date props 삭제
  document.getElementById('root')
);

생명주기 메서드

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  } 
  
  //컴포넌트가 마운트(렌더링?)된후 실행되는 메서드
  componentDidMount() {
    this.timer = setInterval(() => this.tick(),1000);
  } //마운트되면 타이머 실행

  //컴포넌트가 언마운트(삭제)되기 전 실행되는 함수
  componentWillUnmount() {
    clearInterval(this.timerID);
  } //언마운트되기 전 타이머 clear
  
  tick() {
    this.setState({date: new Date()});
  }
  
  render() { 
    return <div>Hello, {this.state.date.toLocaleTimeString()}!</div>;
  } 
}

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

State를 올바르게 사용하기

  • 직접 State를 수정하지 말고 setState를 사용할것
  • State 업데이트는 비동기적일 수도 있습니다.
    • this.state.counter가 비동기적으로 업데이트될 수 있기 때문에 아래 코드는 실패할 수 있습니다.
      //wrong
      this.setState({counter: this.state.counter + 1});
    • setState의 인자로 객체가 아닌 함수를 전달하여 해결할 수 있습니다.
      // Correct
      this.setState((state) => ({counter: state.counter + 1}));
  • State 업데이트는 병합됩니다
    constructor(props) {
      super(props);
      this.state = {
        posts: [],
        comments: []
      };
    }
    • this.setState({comments})는 this.state.posts에 영향을 주진 않지만 this.state.comments는 완전히 대체됩니다.

데이터는 아래로 흐릅니다

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

6. 이벤트 처리하기

  • React의 이벤트는 소문자 대신 캐멀 케이스(camelCase)를 사용합니다.
  • JSX를 사용하여 문자열이 아닌 함수로 이벤트 핸들러를 전달합니다.
//예시
<button onClick={activateLasers}>
  Activate Lasers
</button>

0개의 댓글