2019.09.30 React

Dan.kimhaejun·2019년 9월 30일
0

1. React?


2. ES6?

  • ES6 문법을 알아야 리액트가 편해진다.

- Destructuring

- spread operator

- rest parameters

- default parameters

- templete literals

- arrow function

- for-of loop


3. JSX?

  • 자바스크립트의 확장 문법

- 반드시 하나의 엘리먼트로 감싸야 한다.

///요고는 안됩니다
<div>
 	<h2>안녕하세요</h2>
</div>
<div>
 	<h2>Hello,</h2>
</div>
// 요고는 안됩니다

- 자바스크립트 코드를 적용할때 { } 안에 작성한다.

- JSX내부에선 if문을 사용할 수 없다.

  • IIFE
  • 삼항연산자

- 엘리먼트의 클래스 이름은 className 을 사용한다.

  • ES6 문법에 class가 있기 때문에 혼용 방지

4. props?

- 부모 컴포넌트가 자식 컴포넌트에게 넘겨주는 값

  • 자식 컴포넌트는 props를 받아오기만 할 수 있다.
  • 받아온 props는 직접 수정이 불가하다.

5. state?

- state 값 변경(setState메서드 사용) => render() 함수 실행

- 컴포넌트 내부에서 선언하며 내부에서 값을 변경 할 수 있다.

import React, { Component } from 'react';

export default class Counter extends Component {
  state = { // state는 constructor 함수 안에서도 선언 가능
    count : 0
  }
  constructor(props) {
    super(props);
    this.handleIncreaseBtn = this.handleIncreaseBtn.bind(this);
  }
  handleIncreaseBtn() { // 일반 함수를 사용할때는 bind가 필수
    this.setState({
      count: this.state.count + 1
    });
  }
  handleDecreaseBtn = () => { // 화살표 함수에서는 생략 가능
    this.setState({
      count: this.state.count - 1
    });
  };

  render() {
    return (
      <div>
        <div>{this.state.count}</div>
        <input
          type='button'
          value='increase'
          id='increaseBtn'
          onClick={this.handleIncreaseBtn}
        />
        <input
          type='button'
          value='decrease'
          id='decreaseBtn'
          onClick={this.handleDecreaseBtn}
        />
      </div>
    );
  }
}

- 화살표함수를 사용하여 this가 풀리는 것을 방지

  • constructor함수내부에 bind로 this를 묶어줘도 됩니다.
this.handleIncreaseBtn = this.handleIncreaseBtn.bind(this)

6. Life Style?

컴포넌트가 브라우저 상에서

1. 나타날 때

  • 컴포넌트가 브라우저 상에서 나타날 때
  • state, context, defaultProps 저장 >>> render() >>> componentDidMount()
  • constructor()
  • render()
  • componentDidMount()
    • componentDidMount에서는 DOM에 접근할 수 있습니다. 그래서 여기에서는 주로 AJAX 요청을 하거나, setTimeout, setInterval같은 행동을 합니다.
    • 이벤트를 연결 할 때
    • 외부 라이브러리를 연동할 때
    • 컴포넌트에 필요한 데이터를 요청 할 때
import React, { Component } from 'react'

export default class LifeCycle extends Component {
  constructor(props) {
    super(props)
    console.log('1111111111  constructor')
  }

  componentDidMount = () => {
    console.log('3333333333  componentDidMount')
  }
  render() {
    console.log('2222222222  render')
    const check = console.log('it will be rendered between 2 and 3')
    return (
      <div>
        라이프 사이클 확인 중입니다.
        {check}
      </div>
    )
  }
}


2. 업데이트 될 때

  • propsstate 값이 바뀔 때
  • shouldComponentUpdate()
    • false의 경우 랜더가 되지 않고 화면이 바뀌지 않음
    • 특정한 상황에서만 업데이트를 하고 싶은 경우 (예) 새 글이 올라오지 않으면 업데이트하지 않는다)

3. 사라질 때

  • 컴포넌트가 브라우저 상에서 사라질 때

- 라이프사이클은 클래스컴포넌트에서만 실행 (함수형에서는 실행되지 않는다)

profile
제가 겪은 이슈에 대해서 정리합니다. 기억보다는 기록이 더 낫다고 생각합니다.

0개의 댓글