State와 Lifecycle의 정의
state : 상태, 리액트 Components의 변경가능한 데이터(상태), 개발자가 정의함, 렌더링이나 데이터 흐름에 사용되는 값만 state에 포함시켜야함(성능저하), javascript 객체, 직접 수정 불가
class LikeButton extends React.Component{
constructor(props){ //클래스가 생성될때 실행되는 함수
super(props);
this.state={
liked: false
}
}
}
//직접 수정 불가
//state 직접 수정(잘못된 사용법)
this.state={
name: 'Inje'
};
//setState 함수를 통한 수정(올바른 사용법)
this.setState({
name: 'Inje'
});
Lifecycle : 리액트 Component의 생명주기, Component가 계속 존재하는 것이 아니라 시간의 흐름에 따라 생성되고 업데이트 되다가 사라진다.

(실습) state 사용하기 한번더 보기
//Noti.jsx
import React from "react";
const styles = {
wrapper: {
margin: 8,
padding: 8,
display: "flex",
flexDirection: "row",
border: "1px solid grey",
borderRadius: 16,
},
messageText: {
color: "black",
fontSize :16,
},
};
class Noti extends React.Component {
constructor(props){
super(props);
this.state = {};
}
componentDidMount(){
console.log(`${this.props.id} componentDidMount() called.`); //생성
}
componentDidUpdate(){
console.log(`${this.props.id} componentDidUpdate() called.`); //업데이트
}
componentDiUnmount(){
console.log(`${this.props.id} componentDiUnmount() called.`); //사망
}
render() {
return (
<div style={styles.wrapper}>
<span style={styles.messageText}>{this.props.message}</span>
</div>
)
}
}
export default Noti;
//NotiList.jsx
import React from "react";
import Noti from "./Noti";
const reserveNoti = [
{
id: 1,
message: "안녕하세요, 오늘일정입니다.",
},
{
id: 2,
message: "점심시간입니다.",
},
{
id: 3,
message: "곧 미팅입니다.",
},
];
var timer;
class NotiList extends React.Component {
constructor(props){
super(props);
//초기화
this.state = {
notifications: [],
};
}
componentDidMount(){
const {notifications} = this.state;
timer = setInterval(() => {
if(notifications.length < reserveNoti.length) {
const index = notifications.length;
notifications.push(reserveNoti[index]);
//state업데이트
this.setState({
notifications: notifications,
});
}else {
this.setState({
notifications: [],
});
clearInterval(timer);
}
}, 1000);
}
render() {
return (
<div>
{this.state.notifications.map((notifications) => {
return (
<Noti
key = {notifications.id} //구분을 위한 id
id = {notifications.id}
message = {notifications.message}
/>
)
})}
</div>
);
}
}
export default NotiList;
root.render(
<React.StrictMode>
<NotiList />
</React.StrictMode>
)
chrome 브라우저의 React Developer Tools 사용권장

반응형
'REACT > [inflearn] 처음만난 리액트' 카테고리의 다른 글
8강. Handling Events (0) | 2022.11.09 |
---|---|
7강. Hooks (0) | 2022.11.08 |
5강. Components and Props (0) | 2022.11.03 |
4강. Rendering Elements (0) | 2022.11.02 |
3강. JSX (0) | 2022.10.28 |