inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

처음 만난 리액트(React)

unmount 관련 질문

495

김종운

작성한 질문수 2

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 때문에 그런건가요?

HTML/CSS javascript react

답변 2

0

김종운

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

1

Inje Lee (소플)

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

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

Inje Lee (소플)

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

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

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

강의가 삭제되었다고 합니다

0

106

1

이거 왜 존재하지 않는다고 뜨는건가요

0

133

1

존재하지 않는 수업이라고 떠요

0

182

1

안드로이드 에뮬레이터 오류

0

100

1

교재 구입해서 강의 들으려고 하는데 커리큘럼이 없어졌어요.

0

125

1

prevIsConfiromed 질문

1

141

2

chapter14 잘이해가 되지않습니다..

1

135

2

2025년 3월 리액트버전

1

201

2

npm 설치 오류

1

174

1

chapter_07 콘솔로그 질문드려요~!

1

127

2

안녕하세요 미니블로그 실습 질문드립니다.

1

178

3

에러가 떠요

1

218

3

Chapter6 질문 드립니다

1

209

2

실습 코드 있을까요?

1

205

2

상태가 업데이트될때 컴포넌트 최상단의 console.log 코드가 두번 실행되는 이유가 궁금합니다.

1

233

2

npx create-react-app my-app 명령어 입력이 잘못된 것 같습니다

0

307

3

이름과 코멘트 줄바꿈이 안 됩니다.

0

139

1

버튼이 안 뜹니다

0

303

2

npx create-react-app my-app

1

470

2

jsx 코드 작성해보기에서 index.js 수정 후 에러 뜹니다.

1

375

3

Chapter_05 터미널, 리액트 에러

0

193

2

npx create-react-app my-app 명령어 반응없음

1

432

3

import 코드 에러

1

214

1

백틱

1

121

1