
state๋ ๊ฐ๋ฐ์๊ฐ ์ ์ํ๋ฉฐ
๋ ๋๋ง์ด๋ ๋ฐ์ดํฐ ํ๋ฆ์ ์ฌ์ฉ๋๋ ๊ฐ๋ง state์ ํฌํจ์์ผ์ผํจstate๋ JacaScript์ ๊ฐ์ฒด์ด๋ค.
class LikeBtn extends React.Component { constructor(props) { super(props); this.state = { liked: flase }; } }state๋ ์ง์ ์์ ํ ์ ์์ผ๋ฏ๋ก setState ํจ์๋ฅผ ํตํด์ ๋ณ๊ฒฝํด์ผํจ
Class ์ปดํฌ๋ํธ ๊ฐ๋ ์์ ๊ธฐ์ตํ ๊ฒ์ด๋ฏ๋ก ์ด๋ฐ ๊ฒ์ด ์๋ค+์ปดํฌ๋ํธ ๋ง์ง๋ง ํน์ง๋ง ์๊ฐํด๋๊ธฐ

์ถ์: Mounting, ์ปดํฌ๋ํธ state ํธ์ถ๋จ
์ธ์: Updating
์ฌ๋ง: Unmounting, ์์ ์ปดํฌ๋ํธ์์ ํด๋น ์ปดํฌ๋ํธ๋ฅผ ๋์ด์ ์ฌ์ฉํ์ง ์๊ฒ ๋ ๋
Component๊ฐ ๊ณ์ ์กด์ฌํ๋ ๊ฒ์ด ์๋๋ผ, ์๊ฐ์ ํ๋ฆ์ ๋ฐ๋ผ ์์ฑ๋๊ณ ์ ๋ฐ์ดํธ ๋๋ค๊ฐ ์ฌ๋ผ์ง๋ค
const styles = {
wrapper: {
margin : 8,
padding: 8,
display: "flex",
flexDirection: "row",
border: "1px solid gray",
borderRadius: 16,
},
messageText: {
color: "black",
fontSize: 16,
},
};
class Notification extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount(){
console.log(`${this.props.id} "componentDidMount() called."`) };
componentDidMount(){
console.log(`${this.props.id} "componentDidUpMount() called."`)};
componentWillUnmount(){
console.log(`${this.props.id} "componentWillUnMount() called."`)};
render(){
return(
<div style = {styles.wrapper}>
<span style={styles.messageText}>{this.props.message}</span>
</div>
);
}
}
export default Notification;
import Notification from "./Notification";
const reservedNotifications = [
{
id:1,
message: "์๋
ํ์ธ์ ์ค๋ ์ผ์ ์
๋๋น",
},
{
id:2,
message: "์ ์ฌ์์ฌ ์๊ฐ์
๋๋ค",
},
{
id:3,
message: "์ด์ ๊ณง ๋ฏธํ
์ด ์์๋ฉ๋๋ค",
},
];
var timer;
class NotificationList extends React.Component {
constructor(props){
super(props);
this.state={
notifications: [], //state์์ ์ด๊ธฐํ
};
}
componentDidMount() {
const {notifications} = this.state;
timer = setInterval(() => { //1์ด๋ง๋ค ์ ํด์ง ๋ฐฐ์ด ์ํ
if(notifications.length<reservedNotifications.length){
const index = notifications.length;
notifications.push(reservedNotifications[index]);
this.setState({ //state ์
๋ฐ์ดํธ ํ๊ธฐ ์ํด์
notifications: notifications,
});
}else{
this.setState({
notifications: [],
});
clearInterval(timer);
}
}, 1000);
}
render() {
return(
<div>
{this.state.notifications.map((notification) => {
return (
<Notification
key={notification.id}
id={notification.id}
message={notification.message}
/>
);
})}
</div>
);
}
}