이 글은, 노마드코더의 "ReactJS로 영화 웹 서비스 만들기"를 공부한 내용을 수강자 입장에서 필기한 것으로,
다소 불친절한 설명이 있을 수 있음을 미리 알립니다.
함수들을
function component라고 칭한다.React.Component를 상속한 App 클래스 생성. React Component는 자동적으로render메소드를 실행한다. 동시에state라는 오브젝트를 가지고 있다. 여기에는 계속 변하는 데이터가 들어가게 된다.
state는 무엇인가?
컴포넌트 내부에서 자체적으로 읽고, 업데이트할 수 있는 값을 사용하기 위해 state가 존재한다.
모든 리액트 컴포넌트 안에 존재할 수 있는 오브젝트이다(필수는 아니므로 없어도 된다)
컴포넌트 내 state가 변경될때마다 해당 컴포넌트는 다시 렌더링된다(=render()함수가 실행된다)
state를 선언하는 방법
원래는 생성자(constructor) 안에 선언해야 하지만, 생성자 밖에 다음과 같이 선언할 수 있다.
출처:
https://codingmania.tistory.com/280
class App extends React.Component {
state = {
count: 0,
};
render() {
return <h1>The number is: {this.state.count}</h1>;
}
}결과

import React from "react";
class App extends React.Component {
state = {
count: 0,
};
render() {
return (
<div>
<h1>The number is: {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
);
}
add = () => {
console.log("add");
};
minus = () => {
console.log("minus");
};
}
export default App;this.add()을 사용하면, 시작과 동시에 add를 콘솔에 한번 출력하지만
this.add를 사용하면 클릭할 때마다 add가 실행되게 된다.
실행 결과

# 3.1. All you Need to Know About State
add = () => {
this.state.count += 1;
};
minus = () => {
this.state.count -= 1;
};state의 변수를 직접 변경할 수 없다.
직접적으로 변경하면 render 함수가 자동으로 실행되지 않으므로, 뷰가 동적인 변경이 되지 않는다.
위와같이 코드를 실행하면 다음과 같은 경고가 발생한다.

state값을 변경하는 방법
add = () => {
this.setState({ count: this.state.count + 1 });
};
minus = () => {
this.setState({ count: this.state.count - 1 });
};- 버튼을 클릭하여 add함수를 실행하면,
setState메소드가 실행되고, state의count값이 변경되는 동시에render함수를 자동으로 실행한다. - 여기서도
this.state.xxx를 직접 사용하는 것은 바람직하지 않으므로, 다음과 같이 수정해준다.
add = () => {
this.setState((current) => ({ count: current.count + 1 }));
};
minus = () => {
this.setState((current) => ({ count: current.count - 1 }));
};'JavaScript > React' 카테고리의 다른 글
| React Axios로 API에서 받아온 데이터 확인 # 4.1. Rendering the Movies (0) | 2020.06.29 |
|---|---|
| React Axios로 API 가져오기 #4.0. Fetching Movies from API (0) | 2020.06.29 |
| #3.2. Component Life Cycle (0) | 2020.06.29 |
| React PropTypes 사용법: #2.4 Protection with PropTypes (0) | 2020.06.29 |
| # 2.2 Dynamic Component Generation #2.3 map Recap (0) | 2020.06.29 |