ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2020/11/19 - TIL(React 공식문서 파헤치기2)
    Develop/React 2020. 11. 19. 13:20

     

     

     

     

     

     

    State and Lifecycle

     

    State와 Lifecycle은 class컴포넌트에서만 사용이 가능했으나, 리액트 최신 버전에서는 함수 컴포넌트에서도 리액트 훅(Hook)을 사용하여 State와 Lifecycle 사용이 가능하다고 한다. 하지만 아직 훅을 배우지 않아서 class 컴포넌트에서 밖에 다루지 못할 것 같다.

     

     

     

    State란?

    State는 props와 같이 App 컴포넌트의 렌더링 결과물에 영향을 주는 데이터를 갖고있는 객체이다.

    props는 컴포넌트에 전달이 되는 반면, 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>
        );
      }
    }
    
    ReactDOM.render(
      <Clock />,
      document.getElementById('root')
    );

    클래스 컴포넌트는 항상 props로 기본 constructor를 호출해야한다.

    반환되는 React element는 state객체의 요소에 직접 접근이 가능하다.

     

     

     

    Lifecycle(생명주기) 메서드를 클래스에 추가하기.

    React 컴포넌트는 생명주기 메서드가 있다. 생명주기 메서드는 컴포넌트가 실행되거나 업데이트되거나 제거될 때, 특정한 이벤트를 발생시킨다.

     

     

    • componentDidMount() 메서드는 컴포넌트 출력물이 DOM에 렌더링 된 후에 실행됩니다.
    • componentDidUpdate() 메서드는 컴포넌트에서 setState()등에 의해 상태가 업데이트되면 실행됩니다.
    • componentWillUnmount() 메서드는 컴포넌트가 제거되기 직전에 실행됩니다.

     

     

    State 올바르게 사용하기

     

    직접 state를 수정하지 않는다.

    //bad
    this.state.comment = 'Hello'
    
    //good
    this.setState({comment : 'Hello'});

    state를 직접 수정하게 되면 컴포넌트를 다시 렌더링 하지 않기 때문에 setState()를 사용한다.

     

     

     


     

    이벤트 처리하기

     

    React 엘리먼트에서 이벤트를 처리하는 방식은 DOM 엘리먼트에서 이벤트를 처리하는 방식과 매우 유사하지만 몇 가지 문법 차이가 있다.

     

    • React의 이벤트는 소문자 대신 낙타 표기법(camelCase)을 사용한다.
    • JSX를 사용하여 문자열이 아닌 함수로 이벤트 핸들러를 전달한다.
    <button onClick={this.handleClick}>
      Activate Lasers
    </button>

     

     

    class Toggle extends React.Component {
      constructor(props) {
        super(props);
        this.state = {isToggleOn: true};
    
        // 콜백에서 `this`가 작동하려면 아래와 같이 바인딩 해주어야 합니다.
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick() {
        this.setState(state => ({
          isToggleOn: !state.isToggleOn
        }));
      }
    
      render() {
        return (
          <button onClick={this.handleClick}>
            {this.state.isToggleOn ? 'ON' : 'OFF'}
          </button>
        );
      }
    }
    
    ReactDOM.render(
      <Toggle />,
      document.getElementById('root')
    );

     

     


    조건부 렌더링

    React에서 조건부 렌더링은 JavaScript의 조건 처리와 같이 동작한다. if 나 조건부 연산자와 같은 JavaScript 연산자를 현재 상태를 나타내는 엘리먼트를 만드는 데 사용할 수 있다.

     

    function UserGreeting(props) {
      return <h1>Welcome back!</h1>;
    }
    
    function GuestGreeting(props) {
      return <h1>Please sign up.</h1>;
    }

    위 코드와 같이 두 컴포넌트가 있을 때 if 문을 활용하여 둘 중 하나를 렌더링 할 수 있다.

    function Greeting(props) {
      const isLoggedIn = props.isLoggedIn;
      if (isLoggedIn) {
        return <UserGreeting />;
      }
      return <GuestGreeting />;
    }
    
    ReactDOM.render(
      // Try changing to isLoggedIn={true}:
      <Greeting isLoggedIn={false} />,
      document.getElementById('root')
    );

     

     

    논리 && 연산자로 if를 인라인으로 표현하기

     

    JSX안에는 중괄호를 이용해서 JavaScript 표현식을 포함할 수 있고, 그 안에 && 연산자를 사용하여 조건부를 넣을 수 있다.

     

    function Mailbox(props) {
      const unreadMessages = props.unreadMessages;
      return (
        <div>
          <h1>Hello!</h1>
          {unreadMessages.length > 0 &&
            <h2>
              You have {unreadMessages.length} unread messages.
            </h2>
          }
        </div>
      );
    }
    
    const messages = ['React', 'Re: React', 'Re:Re: React'];
    ReactDOM.render(
      <Mailbox unreadMessages={messages} />,
      document.getElementById('root')
    );

     

    &&뒤의 엘리먼트는 조건이 true일 때만 출력된다. 만약 조건이 false라면 React는 이를 무시하게 된다.

     

     

    조건부 연산자로 if-else 구문 인라인으로 표현하기

     

    JavaScript의 삼항 조건 연산자 구문과 동일한 방법으로 표현이 가능하다.

    render() {
      const isLoggedIn = this.state.isLoggedIn;
      return (
        <div>
          The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
        </div>
      );
    }

     


     

Designed by Tistory.