댓글 기능 구현 중 발생한 시행착오.
<form
className="reply__form"
onSubmit={(e) => {
addReplyInputToInputArray(e);
}}
>
<i className="fa-regular fa-face-angry"></i>
<input
required
type="text"
placeholder="댓글 달기..."
value={replyInputValue}
onChange={(e) => {
setReplyInput(e.target.value);
}}
/>
<button>게시</button>
</form>
<ul className="reply__window">
{replyInputArray.map((data, i) => {
return (
<SetReply
data={data}
index={i}
goodCountArray={goodCountArray}
setGoodCountArray={setGoodCountArray}
/>
);
})}
</ul>
하트를 클릭할 때마다 좋아요 개수가 올라가는 기능을 구현중이었다.
1. 폼이 submit 될 때마다 inputValue어레이에 inputValue 하나씩 추가
2. 1번의 어레이에 map 메소드를 통해 댓글 컴포넌트 생성. 댓글 컴포넌트 생성시, map을 통해 각각의 컴포넌트 댓글마다 고유의 index값을 전달
3. 각 댓글들의 좋아요 개수를 담을 array 추가 생성
const [goodCountArray, setGoodCountArray] = useState([]);
4. 댓글이 생성될 때마다 그 array에 '0'이 푸쉬됨. 세 개의 댓글이 추가된 상태라면, goodCountArray는 [0, 0, 0] 인 상태.
각 댓글은 각각의 인덱스값을 통해 그 어레이의 값을 받아서 씀. ex) 2번째 댓글의 좋아요 수 = goodCountArray[2]
5. 하트 버튼 클릭시 각 댓글의 인덱스에 맞게 배열안의 숫자가 + , - 됨.
2번째 댓글에 하트를 눌렀다면
goodCountArray는 [0, 0, 0] 에 2번째 인덱스, 즉 props.index 자리에 숫자 1 이 들어 있는 인덱스(인덱스가 0번부터 시작하기 때문) 요소에 +1이 되는 것.
const newGoodCount = [...props.goodCountArray];
newGoodCount[props.index] = props.goodCountArray[props.index] + number;
props.setGoodCountArray(newGoodCount);
이렇게 하트 클릭시 좋아요 숫자가 증가하고 재클릭시 감소하는 기능까지는 구현이 되었는데,
- 4번 과정 : 댓글이 생성될 때마다 그 array에 '0'이 푸쉬됨. 세 개의 댓글이 추가된 상태라면, goodCountArray는 [0, 0, 0] 인 상태.
이 단계에서 문제가 생겼다.
컴포넌트가 마운트 될 때마다 goodCountArray에 0이 푸쉬되야 했기 때문에
useEffect 를 이용해서 아래처럼 0이 추가되게 하였는데
useEffect(() => {
goodCountArrayPushing();
});
const goodCountArrayPushing = () => {
const goodCountbase = [...props.goodCountArray];
goodCountbase.push(0);
props.setGoodCountArray(goodCountbase);
};
댓글이 하나 마운트 되는 순간부터 goodCountArrayPushing(); 함수가 무한으로 호출되었다.
const goodCountArrayPushing = () => {
const goodCountbase = [...props.goodCountArray];
goodCountbase.push(0);
props.setGoodCountArray(goodCountbase);
}, [];
대괄호 [] 디펜던시를 추가하여 해결한 줄 알았으나, 또 다른 문제점이 생겼다.
첫번째 컴포넌트 외의 좋아요 개수가 올라가지 않았다.
댓글 생성 시 한번만 작동하고, 그 이후의 댓글들에 대해서는 {하트 클릭 - 좋아요 수 +} 기능이 작동하지 않았다.
즉 하나의 댓글 컴포넌트가 마운트 되고 난 뒤, 다음 댓글 부터는 유즈이펙트 안의 함수가 실행되지 않았다는 것이다.
//댓글 컴포넌트의 변수 선언 부분.
function SetReply(props) {
const [goodCountArray, setGoodCountArray] = useState([]);
}
좋아요 의 숫자를 관리하는 어레이가 댓글 컴포넌트 안에 있었던 것이 문제였다.
댓글이 마운트 될 때마다, useState를 통해 값이 ([]) 되었다.
즉, 0이 푸쉬가 되었다가도, 다음 댓글에서 다시 선언을 []로 해주었기 때문에 계속해서 공백으로 초기화되었던 것.
const [goodCountArray, setGoodCountArray] = useState([]);
댓글 컴포넌트 안에서 선언하는게 아닌,
페이지에서 한번 만 선언하고 각 컴포넌트에 전달해 준 뒤, 컴포넌트에서 프롭스로 받아오는 식으로 문제를 해결하였다.
const newGoodCount = [...props.goodCountArray];
newGoodCount[props.index] = props.goodCountArray[props.index] + number;
props.setGoodCountArray(newGoodCount);
'Frontend Study - 2 > 시행착오' 카테고리의 다른 글
프로젝트 리뷰 리체크 (0) | 2022.07.23 |
---|