티스토리 뷰

[처음 만난 리액트] 섹션 6. State and Lifecycle

 

6강. State and Lifecycle

 

가장 중요한 부분 중 하나.

 

클래스 컴포넌트와 관련됨 (함수 컴포넌트에서도 사용)

 

State (상태)

 

리액트 Component 의 상태 !!!!!

리액트 Component 의 변경 가능한 데이터. -> State

개발자가 정의함

 

렌더링이나 데이터 흐름에 사용되는 값만 state 에 포함시켜야 함

 

state는 JS 객체이다.

 

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

 

다음과 같은 예제가 있다.

모든 클래스 컴포넌트에는 constructor 라는 함수가 존재한다. (생성자)

클래스가 생성될 때 실행되는 함수이다.

this.state = 상태 정의하는 부분.

 

state는 직접 수정할 수 없다. (하면 안 된다.)

 

//state 를 직접 수정 (잘못된 사용법)
this.state = {
	name: 'Inje'
};

//setState 함수를 통한 수정 (정상적인 사용법)
this.setState({
	name: 'Inje'
});

 

컴포넌트 렌더링과 관련이 있기 때문에 마음대로 변경하면 작동에 문제가 생길 수 있다.

 

Lifecycle (생명주기)

 

리액트 Component 의 생명 주기 (출생, 인생, 사망 존재)

 

 Mounting -> Updating -> Unmounting

 

 

상위 컴포넌트에서 현재 컴포넌트를 더이상 표시할 수 없을 때 Unmounting 된다.

 

Component 가 계속 존재하는 것이 아니라, 시간의 흐름에 따라 생성되고 업데이트 되다가 사라진다.

 

State 사용하기 (실습)

 

 

import React from "react";
import Comment from "./Comment";

const comments = [
  {
    name: "집",
    comment: "가고싶다.",
  },
  {
    name: "살",
    comment: "빼자.",
  },
  {
    name: "힝",
    comment: "구리퐁퐁.",
  },
];

function CommentList(props) {
  return (
    <div>
      {comments.map((comment) => {
        return <Comment name={comment.name} comment={comment.comment} />;
      })}
    </div>
  );
}

export default CommentList;

 

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;

 

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

import NotificationList from "./chapter_06/NotificationList";

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

reportWebVitals();

 

Mount, Update, Unmount

 

componentDidMount() {
    console.log(`${this.props.id} componentDidMount() called.`);
  }

  componentDidUpdate() {
    console.log(`${this.props.id} componentDidUpdate() called.`);
  }
  componentWillUnmount() {
    console.log(`${this.props.id} componentWillUnmount() called.`);
  }

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함