★수업3-0
state
state : 변하는 데이터를 관리하는 게 state야
class component는 return을 가지지 않아 대신 render를 가짐
따라서, render 안에 return을 쓴다
class component는 class이며, react component로부터 확장된다.
react는 자동적으로 class component의 render method를 실행한다.
state는 object이다.
state에는 바꾸고 싶은 data를 넣는다.
button에는 onClick이라는 prop이 기본적으로 있다.
this.add()에서 ()는 즉시 함수를 호출해라는 것이고,
this.add는 click했을 때만 함수를 호출하는 것이다.
-function component와 class component를 하는 이유?
function은 props 를 쓰기 위해서(정적인 데이터 사용)
class는 state를 통해서 동적인 데이터를 사용하기 위해서
이 state는 object 이다. state는 계속 변하고 0이 되고 바뀌는 데이터
바뀌는 데이타는 state에 넣는다
-const, f(x)는 그냥 {} 안에 쓰지만,
state는 {this.state.count} 이런 식으로 써줘야 한다.
render안에 쓰고 싶으면
★수업 3-1 / 3-2
1. class component는 return을 갖지 않고
render()라는 함수를 갖고 그 안에 return을 갖는다
2. state를 사용하는 건 값을 변경하기 위해서
state에서 직접 바꾸지 않고 setstate를 통해서 바꾼다
3. life cycle method는 기본적으로 react가 component를 생성하는 그리고 없애는 방법
component가 update될 때 호출되는 다른 function이 있어
mounting : 태어나는 것과 같아
updating : 일반적인 업데이트
unmounting : component가 죽는 걸 의미해, component는 페이지를 바꿀 때 죽어
*mounting
-constructor : javascript에서 class를 만들 때 호출
-componentDidMount : render보다 먼저 호출
-componentDidUpdate : 업데이트 될 때 호출
-componentWillUnmount : component가 떠날 때 호출, 페이지 변경 or 어떤 걸 넣을 떄
-shouldComponentUpdate() :업데이트를 할지 말지 결정하는 것에 대한 것
4. contructor → render → componentDidMount() 순으로 실행
이후에 업데이트가 되면, render → componentDidUpdate 실행
App.js
import React from 'react';
class App extends React.Component{
constructor(props) {
super(props);
console.log("constructor")
}
state = {
count: 0
};
add = () => {
this.setState(current => ({ count: this.state.count + 1 }));
};
minus = () => {
this.setState(current => ({ count: this.state.count - 1 }));
};
componentDidMount() {
console.log("didmount")
}
componentDidUpdate() {
console.log("updated");
}
render() {
console.log("render")
return (
<div>
<h1>The number is: {this.state.count}</h1>
<button onClick={this.add}>add</button>
<button onClick={this.minus}>minus</button>
</div>
)
}
}
export default App;
'React' 카테고리의 다른 글
[React] 간단한 tab(탭) 만들기 (feat. checkbox 추가) (0) | 2024.05.29 |
---|---|
[React] 간단한 투두리스트(todolist) 만들기 (0) | 2024.05.24 |
[React] 노마드 수업 1- 소스 (0) | 2021.08.20 |
[React] 노마드 수업 1 (0) | 2021.08.20 |
[React] 설치 및 시작하기 - 노마드 수업 정리 (0) | 2021.08.20 |