class componet
๊ฐ function component
๋ณด๋ค ๋ ์ฐ๊ธฐ์ ์ด๋ ต๋ค. ํ์ง๋ง function component
๊ฐ ๋์์์๋ class componet
๊ฐ ๋ ๋ง์ด ์ฌ์ฉ๋๋ค.
๊ทธ ์ด์ ๋
1. ๋ง์ ๊ฐ๋ฐ ๋ฌธ์๋ค์ด class componet
๋ก ์์ฑ์ด ๋์ด์๋ค.
2. ๋ฆฌ์กํธ์์ ์ ๊ณตํ๋ lifecycle function
์ผ๋ก ํ ์ ์๋๊ฒ ๋๊ฒ ๋ง๋ค. ๊ทผ๋ฐ lifecycle function
์ด class componet
์์ ๋ฐ์ ๋์์ด ์๋๋ค.
๊ทธ๋์ class componet
์ฌ์ฉํ ๊ธฐ๊ฐ์ด ๋ ๊ธธ์๋ค.
ํ์ง๋ง!! 2019๋
์ดํ๋ถํฐ function component
๋ lifecycle function
์ ์ฌ์ฉํ ์ ์๊ฒ ๋์๋ค.
๊ทธ๋๋ ์์์ผ ํ๋๊น ๊ณต๋ถํ๋ ๊ฒ์ด๋ค.
import { useState,useEffect } from 'react';
import './App.css';
import Box from './component/Box';
function App() {
const [counter, setCounter] = useState(0); //state
const increase =()=>{
setCounter(counter+1);
};
useEffect(()=>{
console.log("useEffect1 Firee");
},[]);
useEffect(()=>{
console.log("useEffect2 Firee", counter);
},[counter]) //์ด๋ ์ด์ ๊ฐ์ ๋ฃ์ผ๋ฉด ์ปดํจํฐ๊ฐ ์ฃผ์ํ๋ค.
return (
<div>
{console.log("render")}
<Box num="1"/>
<div>{counter}</div>
<button onClick={increase}>ํด๋ฆญ!</button>
</div>
);
}
export default App;
import React, { Component } from 'react'
import './App.css';
import BoxClass from './component/BoxClass';
export default class Appclass extends Component {
constructor(props){ // constructor ๋ฆฌ์กํธ์์ ์ ๊ณตํ๋ lifecycle ํจ์ ์ค ํ๋ (์์ฑ์) : ์ปดํฌ๋ํธ๊ฐ ์คํ๋์ ๋ง์ ํจ์์คํ
super(props)
this.state={ // state๋ฅผ ์ ์ธํ๋ค.
counter2 : 0, //์ํ๋ state๋ฅผ ์ ์ธํด ์ฃผ๋ ๊ฒ์ด๋ค.
num:1,
value:0
};
}
/*
function ์ปดํฌ๋ํธ๋ const [counter, setCounter] = useState(0); ์ด๋ฐ ์์ผ๋ก state๋ฅผ ํ๋ํ๋ ๋ฐ๋ก ๋ง๋ค์๋ค๋ฉด
class ์ปดํฌ๋ํธ๋ state๋ผ๋ ๊ฐ์ฒด๋ฅผ ํ๋ ๋ง๋ค๊ณ ๊ทธ ์์ ๋ด๊ฐ ์ํ๋ state๋ฅผ ๋ค ๋ฃ์ผ๋ฉด๋
์์ ๊ฐ์ด ๊ธฐ๋ณธ ๊ตฌ์กฐ๊ฐ ๋ค๋ฅด๋ค.
*/
increase = () =>{
this.setState({counter2:this.state.counter2 + 1 ,
value : this.state.value + 1
});
console.log("increase function", this.state);
}
componentDidMount(){
// api ์ฝ
console.log("componentDidMount");
}
componentDidUpdate(){
console.log("componentDidUpdate", this.state);
}
render() {
console.log("render");
return (
<div>
<div>state: {this.state.counter2}</div> {/* class ์ปดํฌ๋ํธ๋ฅผ ๋ถ๋ฅผ๋๋ counter2๋ง ์ ์ธํ๋ ๊ฒ์ด์๋๋ผ. this.state ๋ฅผ ๋งค๋ฒ ๋ถ์ฌ์ค์ผ ํ๋ค.*/}
<button onClick={this.increase}>ํด๋ฆญ!</button>
<BoxClass num={this.state.value}/>
</div>
)
}
}