• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

unmount 관련 질문

22.11.08 13:55 작성 조회수 347

0

this.state({ notifications: [], });

component들을 unmount 시키는 과정에서 다음과 같은 오류가 나옵니다.

Uncaught TypeError: this.state is not a function

그리고 생명 사이클이 끝나지도 않는데, 로그창은 다음과 같이 나오네요.

Screenshot 2022-11-08 at 1.53.26 PM.png

  1. unmount 시키는 다른 방법이 있는건가요?

  2. 로그창을 보면 굳이 state를 비워주지 않아도 unmount 함수가 호출되는 것 같은데 이것도 StrictMode 때문에 그런건가요?

답변 2

·

답변을 작성해보세요.

0

김종운님의 프로필

김종운

질문자

2022.11.08

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.state({
                    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

안녕하세요, 소플입니다.

NotificationListcomponentDidMount()함수에서 아래 코드가 잘못되었네요~

this.state({
    notifications: [],
});

state를 업데이트 하는 것이기 때문에, this.state가 아니라 this.setState가 되어야 합니다.

this.state라는 함수는 없기 때문에 아래 에러가 발생한 것입니다.

Uncaught TypeError: this.state is not a function

 

그리고 unmount 로그가 출력되는 이유는 StrictMode 때문이 맞습니다.

StrictMode에서는 처음에 컴포넌트를 한 번 mount 시켰다가 unmount시키고,

이후 다시 mount 시키기 때문입니다.

감사합니다.

0

안녕하세요, 김종운님. 소플입니다.

혹시 작성하신 전체 코드를 첨부해주실 수 있을까요?

코드가 있어야 제가 정확한 답변을 해드릴 수 있을 것 같습니다!