Class component
- 지난 시간 코드인 function component를 class component로 바꿨다.
- class component에서는 return이 없고 render메소드에서 화면에 출력한다.
- 또, class component를 쓰는 가장 큰 이유는 state라는 object가 있기 때문이다.
[코드]
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
state = {
count: 0
};
add = () => {
console.log("add");
};
minus = () => {
console.log("minus");
};
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;
[실행 결과]
State 값 바꾸기
add = () => {
this.state.count = 1;
};
minus = () => {
this.state.count = -1;
};
위와 같이 했을 때 결과
- state를 직접 변경하지 말라고 경고메세지가 뜬다.
- 이렇게 하면 리액트가 render 함수를 refresh 하지 않기 때문
setState를 사용하여 값 변경
- setState()를 실행할 때마다 리액트는 render를 rerender하기 때문에 값이 변경된다.
add = () => {
this.setState({count: 1});
};
minus = () => {
this.setState({count: -1});
};
실행결과 add를 누루면 count가 1이되고, minus를 누르면 count가 -1이 된다.
add = () => {
this.setState({count: this.state.count + 1});
};
minus = () => {
this.setState({count: this.state.count - 1});
};
를 하면 count 값이 1씩 증가, -1씩 감소하지만 위는 권장하지 않는 코드이다.
add = () => {
this.setState(current => ({count: current.count + 1}));
};
minus = () => {
this.setState(current => ({count: current.count - 1}));
};
setState는 현재의 state값을 가져옴. 따라서 current.count는 현재 지금의 count 값을 말한다.
Component Life Cycle
- component는 create되고 kill 되는 life cycle이 있다.
- Mounting은 생성되는 것, unmounting은 죽는것, 즉 페이지가 바꿀때 등
- 코드로 확인해보자
[코드]
import React from 'react';
class App extends React.Component {
constructor(props){
super(props);
console.log("Hello. I'm constructor");
}
state = {
count: 0
};
add = () => {
this.setState(current => ({count: current.count + 1}));
};
minus = () => {
this.setState(current => ({count: current.count - 1}));
};
componentDidMount(){
console.log("component rendered");
}
componentDidUpdate(){
console.log("I just updated");
}
componentWillUnmount(){
console.log("Goodbye")
}
render() {
console.log("I'm rendering");
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;
실행순서: 새로고침->Add->Add->Minus
[결과-console]
example
import React from 'react';
class App extends React.Component {
state = {
isLoading: true,
movie: []
};
componentDidMount(){
setTimeout(() => {
this.setState({isLoading: false});
}, 6000);
}
render() {
const { isLoading } = this.state;
return <div>{isLoading ? "Loading" : "We are ready"}</div>;
}
}
export default App;
실행결과: 6초 뒤에 isLoading을 false로 바꿈->6초뒤에 Loading이 we are ready로 바뀜
'🔐 Archive > ReactJS' 카테고리의 다른 글
[ReactJS error] event로 호출되는 함수 내의 함수가 안불러지는 이유? (0) | 2020.03.11 |
---|---|
[ReactJS: 삽질로 얻은 것들] local json파일 불러오기, State에 Props값을 저장하고 싶은 경우 등 (1) | 2020.03.11 |
[weather API] 날씨 API 사용해서 ReactJS로 웹페이지 만들기: 날씨 API 사용하는 방법 (0) | 2020.03.11 |
ReactJS로 웹서비스 만들기 4: Movie app 만들기 (0) | 2020.03.06 |
ReactJS로 웹서비스 만들기 2: Component (0) | 2020.03.05 |