티스토리 뷰

Object Destructuring ( 객체 구조화 )에 대해 알아봅시다.

 

다음과 같은 예제 코드가 있습니다.

import React from "react";

class App extends React.Component {
  state = {
    isLoading: true,
    isMounting: false,
  };
  render() {
    const { isLoading } = this.state;
    return <div>{isLoading ? "Loading..." : "We are ready"}</div>;
  }
}

export default App;

이 코드에서 render() 메서드에 있는 변수 isLoading은 중괄호 안에 선언되어있는데 이건 무슨의미일까요?

  render() {
    const { isLoading } = this.state;
    return <div>{isLoading ? "Loading..." : "We are ready"}</div>;
  }

 

변수가 중괄호안에 있는것과 없는 것으로 차이를 알아봅시다 

const { isLoading } = this.state;
const isLoading = this.state;

 

1) const { isLoading } = this.state;

: this.state에 있는 isLoading의 값을 찾아서 변수에 넣어준다

 

2) const isLoading = this.state;

: this.state의 값 전체를 isLoading에 할당한다

 

state의 값.

  state = {
    isLoading: true,
    isMounting: false,
  };

결과적으로 state에 정의된 값을 고려했을 때

1)번의 { isLoading }은 true값을 갖고

2)번의 isLoading은 this.state의 값 전체(객체)를 할당받게 됩니다.

댓글