React 댓글 추가, 삭제

devMarco·2022년 4월 18일
0

모델링

목록 보기
2/3

reac에서 아주 중요한 부분의 깨달음을 얻게 된 부분이 있었다.순수 자바스크립트와 가장 큰 차이가 자동렌더가 가능한 것이다.
그러므로 새로 랜더를 시킬 때 원본 배열에 바로 푸쉬를 하는 것이 아닌 새로운 배열을 복사해 복사 된 배열에만 내용을 추가하면 되는 것이었다.
그 중 하나가 구조분해할당(...변수)

구조분해할당

mdn에서 말하는 의미로는

구조분해할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.

어렵다. 쉽게 풀어보자면 새로운 복사본을 만들는데 배열에서가 아닌 전부를 분해 따로따로 사용도 가능하고 전체를 다시 복사 할 수도 있다.
아래 코드에서 사용되어 진 예시로는

const newCommentData = [
...commentsList,
{
id: Math.floor(Math.random() * 100),
userId: 'jonghyeok',
text: newComment,
isLiked: false,
createdAt: '16분전',
},
];
setCommentsList(newCommentData);
setNewComment('');
};

const handleDelete = id => {
const index = commentsList.findIndex(value => value.id === id);
const deleteCommentList = [
  ...commentsList.slice(0, index),
  ...commentsList.slice(index + 1),
];
setCommentsList(deleteCommentList);

};

const handleLike = id => {
const index = commentsList.findIndex(value => value.id === id);
const isLikedCommentList = [...commentsList];
if (isLikedCommentList[index].isLiked === true) {
isLikedCommentList[index].isLiked = false;
} else {
isLikedCommentList[index].isLiked = true;
}
setCommentsList(isLikedCommentList);
};

findIndex()

주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다.만족하는 요소가 없으면 -1을 반환합니다.

댓글 추가, 삭제, 좋아요 버튼에 필요한 메서드이다.

새로운 배열을 만들어 리액트에서 자동으로 렌더링이 가능하게 만들어 주는 것이다.push splice 로는 자동으로 렌더링을 가능하게 할 수가 없다. 댓글 하나의 덩어리는 텍스트로만 이루어진 것이 아니고 여러 요소를 가지고 있는 배열 안의 객체로 이루어져있다.이 말인 즉슨 내가 원하는 댓글만 지우기 위해서는 지우고 싶은 배열안의 객체 즉 인덱스에 접근을 해야 한다는 말이다. 그러기 위해서는 댓글이 추가 될 때마다 각각의 댓글마다 고유한ID를 제공해 주어야 한다.그래서 이 아이디와 클릭이벤트가 발생한 아이디를 비교하여 같은 아이디를 가지고 있을 때만 삭제가 가능하도록 하는 것이다.작성된 코드를 보면

const handleDelete = id => {
const index = commentsList.findIndex(value => value.id === id);
const deleteCommentList = [
...commentsList.slice(0, index),
...commentsList.slice(index + 1),
];
setCommentsList(deleteCommentList);
};

삭제하기 원하는 댓글에서 클릭이벤트가 일어날 때 삭제 버튼이 클릭되어지는 고유한id와 삭제가 되어지는 댓글의 고유한id가 같을 때만 삭제 이벤트가 발생을 한다. 여기서 중요한 부분은 내가 원하는 인덱스만 삭제가 되어져야 한다는 것이다.내가 원하는 인덱스를 삭제하기 위해서는 지워질 인덱스를 찾고 그 앞에 있는 인덱스 그리고 그 뒤에 나오는 인덱스들을 구조분해할당하여 앞, 뒤에 인덱스를 합쳐 새로운 배열을 만들어 준다!

const newCommentData = [
      ...commentsList,
      {
        id: Math.floor(Math.random() * 100),
        userId: 'jonghyeok',
        text: newComment,
        isLiked: false,
        createdAt: '16분전',
      },
    ];
    setCommentsList(newCommentData);
    setNewComment('');
  };

  const handleCommentEnter = e => {
    if (e.key === 'Enter') {
      addComment();
    }
  };

  const handleDelete = id => {
    const index = commentsList.findIndex(value => value.id === id);
    const deleteCommentList = [
      ...commentsList.slice(0, index),
      ...commentsList.slice(index + 1),
    ];
    setCommentsList(deleteCommentList);
  };

  const handleMainLike = () => {
    if (mainLike === true) {
      setMainLike(false);
    } else {
      setMainLike(true);
    }
  };

  const handleLike = id => {
    const index = commentsList.findIndex(value => value.id === id);
    const isLikedCommentList = [...commentsList];
    if (isLikedCommentList[index].isLiked === true) {
      isLikedCommentList[index].isLiked = false;
    } else {
      isLikedCommentList[index].isLiked = true;
    }
    setCommentsList(isLikedCommentList);
  };

0개의 댓글