[소플의 처음 만난 리액트] 6장 실습문제
리액트 컴포넌트에서 state와 생명주기를 이용하여 알림 기능을 구현했습니다. NotificationList 컴포넌트에서는 state를 사용하여 알림 데이터를 관리하고, componentDidMount와 componentWillUnmount 함수를 이용하여 알림을 주기적으로 업데이트하고 제거합니다. 이를 통해 알림을 동적으로 표시하고 관리할 수 있습니다.
Dec 30, 2023
Notification.jsx
import React from "react";
// 실습: State와 생명주기 함수 사용하기
const styles = {
wrapper: {
margin: 8,
padding: 8,
display: "flex",
flexDirection: "row",
border: "1px solid grey",
borderRadius: 16,
},
messageText: {
color: "black",
fontSize: 16,
},
};
class Notification extends React.Component {
// Notification 컴포넌트
constructor(props) {
super(props);
this.state = {}; // state에 아무 데이터도 가지고 있지 않음
}
componentDidMount() {
console.log(`${this.props.id} componentDidMount() called.`);
}
componentDidUpdate() {
console.log(`${this.props.id} componentDidUpdate() 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;
NotificationList.jsx
import React from "react";
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에 변경점이 생기면 재렌더링을 한다.
notifications: [], // 빈 배열을 상태에 넣음, 앞으로 사용할 데이터를 state에 넣어서 초기화.
};
}
componentDidMount() {
// 컴포넌트가 마운트 된 직후 실행할 내용
const { notifications } = this.state;
timer = setInterval(() => { // 매 1초마다 정해진 작업 수행
// 미리 만들어둔 알림 데이터 배열 reservedNotification으로부터 데이터를 하나씩 가져와 state에 있는 nptification 배열에 업데이트.
if (notifications.length < reservedNotifications.length) { // 배열의 길이가 reservedNotification과 같아질 때까지 반복
const index = notifications.length; // index를 초기화
notifications.push(reservedNotifications[index]); // 해당 인덱스의 문자열을 배열에 push.
this.setState({
Notifications: notifications, // state를 바꿈
});
} else {
this.setState({
notifications: [], //unmaount 로고 보기 위해 notifications 배열을 비움
});
clearInterval(timer); // 배열의 길이가 같아졌다면 timer를 제거.
}
}, 1000);
}
componentWillUnmount() {
if (timer) { // true로 취급 == Truthy
clearInterval(timer); // unmount된 시점에서도 사라지지 않았다면 타이머가 돌아가지 않게 clear 시킨다.
}
}
render() {
return (
<div>
{this.state.notifications.map((notification) => {
return (
<Notification
key={notification.id}
id={notification.id}
message={notification.message}
/>
);
})}
</div>
);
}
}
export default NotificationList;
핵심 키워드
- state는 컴포넌트의 상태를 변경 가능한 데이터다. 직접적인 변경은 불가능하고 setState() 와 같은 함수를 통해 간접적으로 변경을 해야한다.
- state가 변경될 경우 컴포넌트가 재렌더링 되므로 렌더링과 데이터 흐름에 사용되는 값만 state에 포함시켜야 한다.
- 컴포넌트는 계속 존재하는 것이 아니라 시간의 흐름에 따라 생성되고 업데이트되다가 소멸된다. 컴포넌트가 생성되는 시점을 마운트, 컴포넌트의 props가 변경되는 시점을 업데이트, 컴포넌트를 더 이상 화면에 표시하지 않는 시점을 언마운트라고 한다.
결론!
리액트 컴포넌트에서 state와 생명주기를 이용한 구현이 중요하다는 것을 알 수 있었다.
Share article