Backend
home
🔨

22. (실습) state 사용하기

생성일
2025/01/24 05:52
태그
결과
Notification.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 Notification 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.`); } 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;
JavaScript
복사
NotificationList.jsx
import React from "react"; import Notification from "./Notification"; const reservedNotifications = [ { id: 1, message: "안녕하세요, 오늘 일정을 알려드립니다.", }, { id: 2, message: "점심식사 시간입니다.", }, { id: 3, message: "이제 곧 미팅이 시작됩니다.", }, ]; let timer class NotificationList extends React.Component { constructor(props) { super(props); this.state = { notifications: [], }; } componentDidMount() { const { notifications } = this.state; timer = setInterval(() => { if (notifications.length < reservedNotifications.length) { const index = notifications.length; notifications.push(reservedNotifications[index]); this.setState({ notifications: notifications, }); } else { { this.setState({ notifications: [], }); } clearInterval(timer); } }, 1000); } render() { return ( <div> {this.state.notifications.map((notification) => { return <Notification key={notification.id} // key, id 필수로 추가해주기 id={notification.id} message={notification.message} /> })} </div> ); } } export default NotificationList;
JavaScript
복사