2025년, 코딩은 선택이 아닌 필수!

2025년 모든 학교에서 코딩이 시작 됩니다. 먼저 준비하는 사람만이 기술을 선도해 갑니다~

웹프로그래밍/react

5. State와 생명주기

파아란기쁨1 2022. 6. 14. 10:32
반응형

State란

State는 상태라는 의미를 가지고 있다. 즉 리액트 컴포넌트의 상태를 의미한다.

State를 정의할 때 중요한 점은 '렌더링이나 데이터 흐름에 사용되는 값만 state 에 포함시켜야 한다.'

이 이유는 state 가 변경 될 때마다 컴포넌트가 재 렌더링 되기 때문에 데이터 흐름과 관련이 없는 값을 포함하면 의미 없는 경우에 재렌더링 되고 성능 저하가 나타날 수 있다.

 

 

State 특징

리액트의 state 는 자바스크립트 객체이다.

 

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

}

여기서 constructor 는 생성자를 의미하며 Hello 객체가 생성될 때 state의 liked 가 false 된다.

이렇게 정의 된 이후 state는 다음과 같이 변경을 한다.

this.setState({
	liked:true
});

state 를 변경 할 때는 꼭 setState 를 이용해서 변경 한다.

 

 

생명주기

모든 객체는 생명주기를 가지고 있듯이 리액트 컴포넌트 역시 생명주기를 가지고 있다.

컴포넌트가 생성되는 시점 -> constructor()

컴포넌트가 렌더링 된 이후 -> componentDidMount()

State가 변경되는 경우 -> componentDidUpdate()

소멸되는 시점 -> componentWillUnmount()

 

state와 생명주기 함수 사용하기 예

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>
        );
    }
}

먼저 메시지 컴포넌트를 만든다.

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 {
				notifications.length = 0;
                this.setState({
                    notifications: [],
                });
            }
        }, 1000);
    }

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

메시지 출력 리스트를 보면 

notifications 에 현재의 state 를 가져 온 다음에

notifications 의 길이가 우리가 표현하고 싶은 reservedNotifications 의 길이 보다 작다고 하면 뒤에 해당 아이디 값을 push 해 준 후에 setState 를 이용하여 state 를 변경해 주면 1초에 한문장씩 출력 되는 것을 확인 해 볼 수 있다.

 

 

 

 

 

 

참고

소플의 처음 만난 리액트

 

 

반응형

'웹프로그래밍 > react' 카테고리의 다른 글

6.훅(Hook)  (0) 2022.06.15
4. 컴포넌트와 Props  (0) 2022.06.14
3. 엘리먼트란  (0) 2022.06.13
02. JSX 란  (0) 2022.06.13
01. react 준비  (0) 2022.06.13