본문 바로가기
Front/React

[React] State 사용하기 ( React Developer Tools )

by 오엥?은 2023. 4. 17.
반응형

 

✔  state 사용하기

  • src > chapter_06 > 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 = {};
    }

    render() {
        return (
            <div style={styles.wrapper}>
                <span style={styles.messageText}>{this.props.message}</span>
            </div>
        );
    }
}

export default Notification;

 

  • src > chapter_06 > NotificationList.jsx 만들기
import React from "react";
import Notification from "./Notification";

const reservedNotifications = [
    {
        message: "안녕하세요, 오늘 일정을 알려드립니다.",
    },
    {
        message: "점심식사 시간입니다.",
    },
    {
        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 {
                clearInterval(timer);
            }
        }, 1000);
    }

    render() {
        return (
            <div>
                {this.state.notifications.map((notification) => {
                    return <Notification message={notification.message} />;
                })}
            </div>
        );
    }
}

export default NotificationList;

처음 생성자에서 notifacations 라는 빈 배열을 state 에 넣었다. 이처럼 생성자에서는 앞으로 사용할 데이터를 state 에 넣어서 초기화한다.

 

그 다음 미리 만들어 둔 reservedNotifications 로 부터 알림 데이터를 하나씩 가져와서 notifications 배열에 넣고 업데이트 한다. 여기서 주목할 부분은 state 를 업데이트 하기 위해서 setState 함수를 사용한다는 것이다. 

 

  • index.js 수정
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import Library from './chapter_03/Library';
import Clock from './chapter_04/Clock';
import CommentList from './chapter_05/CommentList';
import NotificationList from './chapter_06/NotificationList';

ReactDOM.render(
  <React.StrictMode>
    <NotificationList />
  </React.StrictMode>,
  document.getElementById('root')
);



// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

  • npm start

 실행하면 setInterval(1000) 을 썼기 때문에 1초 간격으로 화면에 출력된다. 

 

 

 

 

✔  React Developer Tools 사용하기

: react application 을 개발할 때는 개발자도구를 확인하는 것 보다 react 를 위해서 별도로 개발된 React Developer Tools 를 이용하는 것이 더 좋다.

 

  • React Developer Tools 검색하여 Chrome 에 추가하기

 

  • 그럼 react 아이콘 모양으로 Components 와 Profiler 라는 새로운 탭이 생긴다.

- 각 Component 를 누르면 props 와 state 확인이 가능하다. 에러가 뜨는 건 왜 그런지 모르겠으니깐 흐린눈 해야지

 

- Profiler 탭에서는 component 들이 랜더링되는 과정들을 기록하여 단계별로 살펴볼 수 있다. 

이 기능을 이용하면

 

① 어떤 component 가 렌더링 되는지

렌더링 시간이 얼마나 소요되었는지

③ component 가 왜 다시 렌더링 되었는지

 

등을 확인할 수 있다. 이를 통해 불필요하게 렌더링 되거나, 무거운 component 를 찾아서 최적화하여 react application 의 성능을 향상시킬 수 있다.

 

 

 

✔  Lifecycle method 사용하기

  • Notification.jsx

 

  • NotificationList.jsx

id 추가하기

key, id 추가하기

- key : react element 를 구분하기 위한 고유의 값 (map 함수를 쓸 때는 필수적으로 들어가야 함)

 

  • 다시 Notification.jsx

 

  • console 확인

순서대로 log 가 나오는 것을 볼 수 있다. component 가 mount 될 때와 update 될 때의 log 가 출력된다.

에러 뜨는 건 안 보이는 척 할 거다.

 

 

반응형