ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [ReactJS] State and Lifecycle
    Programming/ReactJS 2022. 11. 30. 13:14

    State

    리액트 컴포넌트의 상태라는 의미를 가지는데, 개발자가 직접 정의해서 사용하게 된다. 랜더링이나 데이터 흐름에 사용되는 값만 state에 포함시켜야 한다. 그렇지 않은 경우 컴포넌트의 인스턴스 필드로 정의하면 된다. 하나의 자바스크립트 객체라고 생각하면 된다.

    class LikeButton extends React.Component {
        constructor(props) {
            super(props);
    
            this.state = {
                liked: false
            };
        }
    }

    생성자에서 state를 정의하는데, 그 이후 state를 직접 수정해서는 안된다.

    this.state = {
        name: 'cdd'
    }; // state를 직접 수정
    
    this.setState({
        name: 'cdd'
    }); // setState 함수를 통한 수정

    Lifecycle

    생명주기라는 의미를 가지는데, 컴포넌트가 생성되는 시점(componentDidMount)에서 소멸되는 시점(componentWillUnmount)까지를 의미한다고 생각하면 된다. 컴포넌트를 더 이상 표시할 필요가 없을 때 컴포넌트의 소멸이 이루어진다.


    < Source />

    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()`);
        }
        componentDidUpdate() {
            console.log(`${this.props.id} componentDidUpdate()`)
        }
        componentWillUnmount() {
            console.log(`${this.props.id} componentWillUnmount()`)
        }
    
        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: [],
            }
        }
    
        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);
                }
            }, 2000);
        }
    
        componentWillUnmount() {
    
            if (timer) {        
                clearInterval(timer);        
            }
        }
    
        render() {
            return (
                <div>
                    {this.state.notifications.map((notification) => {
                        return (
                            <Notification
                                key = {notification.id}
                                id = {notification.id}
                                message = {notification.message}
                            />
                        );
                    })}
                </div>
            );
        }
    }
    
    export default NotificationList

    ※ 본 게시글은 소플님의 강의 영상을 참고하여 작성되었습니다. 개인적인 공부 목적으로 사용하고 있고, 문제 시 비공개 전환하도록 하겠습니다.

    'Programming > ReactJS' 카테고리의 다른 글

    [ReactJS] Conditional Rendering  (0) 2022.11.30
    [ReactJS] Handling Events  (0) 2022.11.30
    [ReactJS] Hooks  (0) 2022.11.30
    [ReactJS] Components and Props  (0) 2022.11.30
    [ReactJS] Rendering Elements  (0) 2022.11.29

    댓글