리액트와 ES6의 구조 분해 할당

jh22j9·2020년 8월 29일
2

리액트를 처음 공부할 때 구조 분해 할당이 익숙하지 않아 몹시 헷갈렸었다. 유튜브 튜토리얼을 보고 학습한 내용을 기록한다.

구조 분해 할당(Destructuring assignment)


// App.js
import React from 'react';
import Greet from './Greet'

class App extends React.Component {
  render() {
    return (
      <div>
        <Greet name="Diana" heroName="Wonder Woman" />
      </div>
    )
  }
}

export default App

App 객체에서 정의한 props의 값을 사용하려면 기본적으로 아래와 같이props.key로 쓸 수 있다. 여기에서 keyprops를 정의할 때 임의로 붙인 실제로 우리가 전달하고자하는 value의 이름이다.

// Greet.js
import React from 'react'

const Greet = props => { // App에서 정의한 props가 들어온다. 
  return (
    <div>
      <h1>
        Hello {props.name} a.k.a {props.heroName} // 객체이므로 이렇게 사용할 수 있다. 
      </h1>
    </div>
  )
}

export default Greet

그러나 우리는 ES6에 따라 props를 분해하여 더 심플하게 사용할 수 있다.

함수 컴포넌트에서의 구조 분해 할당

두 가지 방법이 있다.

(1) 함수의 인자 안에서 분해한다.

const Greet = ({ name, heroName }) => { // props 객체가 여기로 전달되므로, 이 자리에서 직접 프로퍼티를 추출할 수 있다. 
  console.log(name) // Diana
  return (
    <div>
      <h1>
        Hello {name} a.k.a {heroName} // value가 출력된다. 
      </h1>
    </div>
  )
}

(2) 함수 본문 안에서 분해한다.

const Greet = props => {
  const { name, heroName } = props;
  return (
    <div>
      <h1>
        Hello {name} a.k.a {heroName}
      </h1>
    </div>
  )
}

클래스 컴포넌트에서의 구조 분해 할당

// App.js
import React from 'react';
import Welcome from './Welcome'

class App extends React.Component {
  render() {
    return (
      <div>
        <Welcome name="Bruce" heroName="Batman" />
      </div>
    )
  }
}
export default App

클래스 컴포넌트에서는 props 또는 state를 보통 render()안에서 분해한다.

(1) Props

// Welcome.js
class Welcome extends Component {
  render() {
    const { name, heroName } = this.props // 사용할 프로퍼티 추출 (여러개 중 일부만 해도 된다) 
    return (
      <h1>
        Welcome {name} a.k.a {heroName}
      </h1>
    )
  }
}

(2) State

// Welcome.js
class Welcome extends Component {
  render() {
    const { name, heroName } = this.props 
    const { state1, state2 } = this.state
    return (
      <h1>
        Welcome {name} a.k.a {heroName}
      </h1>
    )
  } 
}

🔗 [ReactJS Tutorial - 12 - Destructuring props and state]

0개의 댓글