리엑트 기초(?)

pen9508901·2020년 10월 6일
0

사전 지식

ES6

Destructruring

spread operator

rest parameters

default parameters

template literals

arrow function

for-of loop


리엑트

JSX

자바스크립트 확장 문법 

1.반드시 하나의 엘리먼트로 감싸야 한다.
2.자바스크립트를 코드를 적용할 떈 {} 안에 작성한다.
3.삼항연산자 사용
4.className 을 사용


생명주기

마운트 : 아래 메서드들은 컴포넌트의 인스턴스가 생성되어 DOM 상에 삽입될 때에 순서대로 호출됩니다.
- constructor()
- render ()
- componentDidMount()
업데이트 : props 또는 state가 변경되면 갱신이 발생합니다. 아래 메서드들은 컴포넌트가 다시 렌더링될 때 순서대로 호출됩니다
- render()
- componentDidUpdate()
마운트 해제 : 아래 메서드는 컴포넌트가 DOM상에서 제거될 떄에 호출됩니다.
- compnentWillUnmount()

컴포넌트

React가 사용자 정의 컴포넌트로 작성한 엘리먼트를 발견하면 JSX 어트리뷰트와 자식을 해당 컴포넌트에 단일 객체로 전달합니다. 이 객체를 “props”라고 합니다.

주의: 컴포넌트의 이름은 항상 대문자로 시작합니다.

렌더링

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

컴포넌트 합성

컴포넌트는 자신의 출력에 다른 컴포넌트를 참조할 수 있습니다

Welcome을 여러 번 렌더링하는 App 컴포넌트를 만들 수 있습니다.

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

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

props 는 읽기 전용

모든 React 컴포넌트는 자신의 props를 다룰 때 반드시 순수 함수처럼 동작해야 합니다.

State는 props와 유사하지만, 비공개이며 컴포넌트에 의해 완전히 제어됩니다

잠깐 State 를 사용 하기 위해서는 클래스 로 사용해야 한다.

함수에서 클래스로 변환하기
함수 컴포넌트를 클래스로 변환할 수 있습니다.

React.Component를 확장하는 동일한 이름의 ES6 class를 생성합니다.
render()라고 불리는 빈 메서드를 추가합니다.
함수의 내용을 render() 메서드 안으로 옮깁니다.
render() 내용 안에 있는 props를 this.props로 변경합니다.
남아있는 빈 함수 선언을 삭제합니다

class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

render 메서드는 업데이트가 발생할 때마다 호출
같은 DOM 노드로 을 렌더링하는 경우 Clock 클래스의 단일 인스턴스만 사용됩니다. 이것은 로컬 state와 생명주기 메서드와 같은 부가적인 기능을 사용할 수 있게 해줍니다.

이게 무선 말 이고 ??

클래스에 로컬 State 추가하기

render() 메서드 안에 있는 this.props.date를 this.state.date로 변경합니다

class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

초기 this.state를 지정하는 class constructor를 추가합니다.

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>
    );
  }
}

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

요소에서 date prop을 삭제합니다

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

결과

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')
);

생명 주기로 구성 해보기

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      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')
);

Clock이 ReactDOM.render()로 전달되었을 때 React는 Clock 컴포넌트의 constructor를 호출 > Clock이 현재 시각을 표시해야 하기 때문에 현재 시각이 포함된 객체로 this.state를 초기화 > React는 Clock 컴포넌트의 render() 메서드를 호출 >
이를 통해 React는 화면에 표시되어야 할 내용을 알게 됩니다 > React는 Clock의 렌더링 출력값을 일치시키기 위해 DOM을 업데이트 > Clock 출력값이 DOM에 삽입 > React는 componentDidMount() 생명주기 메서드를 호출 > lock 컴포넌트는 매초 컴포넌트의 tick() 메서드를 호출하기 위한 타이머를 설정하도록 브라우저에 요청 > Clock 컴포넌트는 setState()에 현재 시각을 포함하는 객체를 호출하면서 UI 업데이트를 진행
> setState() 호출 덕분에 React는 state가 변경된 것을 인지 > render() 메서드를 다시 호출 > React는 이에 따라 DOM을 업데이트 > Clock 컴포넌트가 DOM으로부터 한 번이라도 삭제된 적이 있다면 React는 타이머를 멈추기 위해 componentWillUnmount() 생명주기 메서드를 호출

주의
직접 State를 수정 X setState() 사용
this.state를 지정할 수 있는 유일한 공간은 바로 constructor입니다.

State 업데이트는 비동적일 수도 있다.
객체보다는 함수를 인자로 사용하는 다른 형태의 setState()를 사용합니다. 그 함수는 이전 state를 첫 번째 인자로 받아들일 것이고, 업데이트가 적용된 시점의 props를 두 번째 인자로 받아들일 것입니다

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

State 업데이트는 병합됩니다.
setState()를 호출할 때 React는 제공한 객체를 현재 state로 병합합니다.

constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
  }
  componentDidMount() {
    fetchPosts().then(response => {
      this.setState({
        posts: response.posts
      });
    });

    fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
  }
profile
생각이란걸해

0개의 댓글