본문 바로가기
FrontEnd/React.js

[React.JS] 함수형 컴포넌트 => 클래스형 컴포넌트

by Chaedie 2022. 8. 12.
728x90
import { useEffect, useState } from 'react';
import Comment from './Comment';
import './Article.scss';

function Article({
  userId,
  profileImg,
  feedContents,
  feedImg,
  commentsListProps,
}) {
  const [loggedInUserId] = useState('chaedong');
  const [commentsList, setCommentsList] = useState([]);
  const [commentContent, setCommentContent] = useState('');

  const inputComment = e => setCommentContent(e.target.value);
  const submitComment = e => {
    e.preventDefault();
    if (commentContent === '') {
      return;
    }
    setCommentsList([...commentsList, commentContent]);
    setCommentContent('');
  };

  useEffect(() => {
    setCommentsList([...commentsListProps]);
  }, []);
import Comment from './Comment';
import './Article.scss';

import React from 'react';

class ArticleClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loggedInUserId: 'chaedong',
      commentsList: [],
      commentContent: '',
    };
  }

  componentDidMount() {
    this.setState({ commentsList: [...this.props.commentsListProps] });
  }

  // TODO
  // 유즈 이펙트에 대해 , 리액트의 생명주기에 대해 아는대로 설명해주세요?

  // useEffect()
  //! 퉁 칠 수 있음
  // componentDidMount;
  // componentDidUpdate;
  // componentWillUnmount;

클래스형 컴포넌트를 배우기 위해

함수형 컴포넌트에서 클래스형 컴포넌트로 변환해 보았습니다.

생활코딩을 통해 배울땐 그냥 이렇구나 하고 넘어간것들을 직접 머릿속에서 인출해보고, 검색해보고, 에러메시지 해결해보면서 조금은 더 잘 알게 된것 같습니다. 특히나 useEffect()를 이해하기 위해 (생명주기 메서드를 배우기 위해) 시작한 클래스형 컴포넌트였는데요. 해당 생명주기들에 대해 어느정도 대략적이나마 이해하게 되어 좋았습니다.

동기랑 같이 공부하니 좋군여 👍👍

대략적으로 이해하기론

componentDidMount(); 는 useEffect(, []) 과 같음
componentDidUpdate(); 는 useEffect(, [update되는 state]) 와 같음
componentwillUnmount();는 useEffect(() => {return 클린업()}, [dependencies] 과 같음

댓글