Project | 인스타그램 클론 코딩 리뷰 (3)

Ryan·2020년 11월 13일
3

Project | Westagram

목록 보기
3/3
post-thumbnail

5. Code Review

3) 자식 Component 주요 코드

(1) FeedList Component

: 좌측 피드 부분의 컴포넌트, 길이가 길기 때문에 주요 코드 부분만 발최했다.
구조분해 할당된 코드를 보여줄 예정이므로 참고

    const { postAccURL, postAccount, feedURL, bodyText, comments, postTime, NumberOfLike } = this.props.feed;
    const { changeLikeButtonColor, changeBookMarkColor, inputCommentInfo } = this.state;
    const { chagelikeButtonColor, chageBookMarkButtonColor, changeAddViewButton, handleDelete, handleInputComment, inputCommentRef} = this;

(1)-1 state 부분

//FeedList.js : FeedList 컴포넌트의 State 부분
  constructor() {
    super();
    this.inputCommentRef = React.createRef();
    this.state = {
      inputCommentInfo: [],
      changeLikeButtonColor: false,
      changeBookMarkColor: false,
      addView: false,
    };
  }
  • inputCommentRef : 댓글의 input으로 받은 값을 담아두는 곳이다.
  • changeLikeButtonColor : 좋아요 버튼을 누르면 색깔이 스위칭하도록 불린값을 담는다.
  • changeBookMarkColor : 북마크 버튼을 누르면 색깔이 스위칭하도록 불린값을 담는다.
  • addView : 피드 바디의 더보기 버튼을 누르면 게시글 전체가 나오도록 한다.

(1)-2 댓글 작성 기능 부분

//FeedList.js : FeedList 컴포넌트의 댓글 작성 폼 
  handleInputComment = (e) => {
    e.preventDefault();
    const commentInfo = [...this.state.inputCommentInfo];
    commentInfo.push({
      postTime: Date.now(),
      user: this.props.profile[0].account,
      sentence: this.inputCommentRef.current.value,
    });
    this.setState({ inputCommentInfo: commentInfo });
    this.inputCommentRef.current.value = '';
  };
//FeedList.js : FeedList 컴포넌트의 댓글 삭제 기능 
  handleDelete = (e) => {
    const commentBox = [...this.state.inputCommentInfo];
    const deleteBox = commentBox.filter(
      (element) => element.postTime !== Number(e.target.id)
    );
    this.setState({ inputCommentInfo: deleteBox });
  };
// -------------생략-------------
//렌더 부분
<form onSubmit={handleInputComment}>
  <input
    type='text'
    className='inputComment'
    placeholder='댓글 달기...'
    ref={inputCommentRef}/>
  <button className='buttonComment'>게시</button>
</form>
  • handleDelete 는 아래 나올 AddComments 라는 컴포넌트로 props를 통해 전달해줄 것이다.
    그때 발생한 event를 이용해서 해당 event가 발생한 id를 제외하고 필터링 해서 댓글 리스트에서 보여줄 것이다.

(1)-2 좋아요 기능 부분

//FeedList.js : FeedList 컴포넌트의 좋아요 버튼 기능
  changelikeButtonColor = () => {
    this.setState({ changeLikeButtonColor: !this.state.changeLikeButtonColor });
  };
// -------------생략-------------
// 색깔 변화 렌더 부분
<button className='feedButton' onClick={chagelikeButtonColor}>
  <svg
    fill={changeLikeButtonColor === true ? '#ff0000' : '#262626'}
    viewBox='생략'>
    <path d='생략'></path>
  </svg>
</button>
// -------------생략-------------
// 카운트 증가하는 렌더 부분
<div className='countFeedLikeStyle'>
  좋아요 {changeLikeButtonColor ? NumberOfLike + 1 : NumberOfLike}</div>

(1)-3 북마크 기능 부분

  changeBookMarkButtonColor = () => {
    this.setState({ changeBookMarkColor: !this.state.changeBookMarkColor });
  };
  • 좋아요 기능과 비슷하므로 렌더부분은 생략

(1)-4 더보기 기능

  changeAddViewButton = () => {
    this.setState({ addView: !this.state.addView });
  };
// -------------생략-------------
//렌더 부분
<span className='foodBodyTextStyle'>
  {this.state.addView
    ? bodyText.split('\n').map((line) => {
    return (
      <>
        {line}<br />
      </>);})
    : bodyText.slice(0, 12)}
  <button onClick={changeAddViewButton} className='addViewButton'>
    {this.state.addView ? null : '더 보기 ...'}
  </button>
</span>
// -------------생략-------------
// 카운트 증가하는 렌더 부분
<button type='button' className='commentButtonTextStyle'>
  댓글 {comments.length}개 모두 보기
</button>

(2) AddComments Component

: 추가되는 댓글의 기본 틀이 되는 컴포넌트

//Main.js : AddComments 컴포넌트의 전체 코드
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import '../../Reset.scss';

class AddComments extends Component {
  render() {
    const { user, sentence, postTime } = this.props.list;
    return (
      <div className='commentButtonBox'>
        <div className='comment'>
          <Link to='/'>
            <span className='largeText heavyWeight'>{user} </span>
          </Link>
          <span className='largeText normalWeight'>{sentence}</span>
        </div>
        <button onClick={this.props.onDelete} id={postTime}>
          ✖️
        </button>
      </div>
    );
  }
}

export default AddComments;
  • profileList 라는 state에는 목업 데이터에서 받아온 계정들의 정보가 담겨있다.
  • 목업 데이터에서 팔로우로 구분된 계정들만 스토리에 보여주기 위해 filter 메서드를 이용하였다.
  • filter 된 계정이 담긴 배열객체들에 Map 메서드를 이용하여 라는 컴포넌트를 반복해서 만들어내었다
  • 삭제 버튼에는 id를 부여해서 부모 컴포넌트에서 삭제 기능(handleDelete)을 실행시킨다.

(3) Comments Component

: 댓글리스트를 보여주는 컴포넌트이다.

import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class Comments extends Component {
  render() {
    return (
      <>
        {this.props.list.map((element, index) => (
          <div className='comment' key={index}>
            <Link to='/'>
              <span className='largeText heavyWeight'>
                {element.commentAcc}{' '}
              </span>
            </Link>
            <span className='largeText normalWeight'>{element.comment}</span>
          </div>
        ))}
      </>
    );
  }
}

export default Comments;
  • 댓글 리스트와 추가되는 댓글 리스트를 합치지 못해서 안타깝다.
    처음부터 계정 정보가 담긴 목데이터에 각 계정의 게시글에 대한 정보까지 구조화를 해놨어야 했던것 같다.

5. 리펙토링 하기

: 리펙토링을 하며 놓쳤던 부분들

  1. console.log 지우기!
  2. 함수 이름, 변수 이름, 클래스 이름
  3. reset.scss & common.scss
  4. Sass nesting 활용
  5. className의 동적 사용
  6. 비구조화 할당, 구조분해 할당(destructuring)
  7. Boolean 데이터 타입의 활용
  8. 반복되는 코드는 Array.map() 활용
  9. inputHandler 함수 합치기 - 계산된 속성명
  10. <a> 대신 <Link> 태그 사용하기
profile
"꾸준한 삽질과 우연한 성공"

4개의 댓글

comment-user-thumbnail
2020년 11월 15일

상혁갓..

1개의 답글
comment-user-thumbnail
2020년 11월 29일

잘보고가요!!! 저도 곧 인스타그램 리액트로 클론해보려고 하는데 코드 공유해주셔서 너무 감사합니다 도움이 많이 됐어요~~!

1개의 답글