const totalCount = likesCount + dislikesCount;
const likesPercentage =(likesCount / totalCount) * 100;
const dislikesPercentage =(dislikesCount / totalCount) * 100;
위처럼 like+dislike를 각각 더한 값을 total count로 만들고,
likes와 dislikes의 Percentage를 계산하였다.
이때, likesCount, dislikesCount, totalCount 의 값이 모두 0이면, 퍼센테이지 계산 값이 '0' 이 아닌 'NaN'으로 출력되는 현상이 일어났다.
하지만 typeof 로 보았을 때 likes, dislikes, total count 모두 '0'이지만 number로 보여졌다.
여기서 정말 이상한 것은 각각 likesPercentage/dislikesPercentage를 typeof 로 출력해 보았을 때는 number로 출력이 되는데, 실제값은 NaN으로 표기되고 있었다.
결론적으로 해당 문제는 JS의 계산방법 때문에 일어난 일이라고 한다.
JS 에서는 0과 0을 나누면 0이 아니라 NaN이 되어 버린다.
const totalCount = likesCount + dislikesCount;
const likesPercentage =
totalCount === 0 ? 0 : (likesCount / totalCount) * 100;
const dislikesPercentage =
totalCount === 0 ? 0 : (dislikesCount / totalCount) * 100;
따라서 삼항연산자를 이용하여 totalCount의 값이 0일 경우에는 계산을 진행하지 않고, 바로 0을 출력하도록 만든 뒤 문제가 해결되었다. 수정 코드는 아래와 같다.
오늘도 잘 해냈다!
'TIL' 카테고리의 다른 글
230828) Input 태그 기본 Style 없애기 (0) | 2023.08.28 |
---|---|
230825) react 에서 image 파일 폴더 생성하고 쉽게 불러오기 (0) | 2023.08.25 |
230823) input type="file"로 사용 시 특정 형식 파일만 업로드 할 수 있게 하는 방법 (0) | 2023.08.23 |
230822) onClick 내부에서 useNavigate를 직접 호출해 사용할 경우 작동 되지 않는 현상 (0) | 2023.08.22 |
230821) React 환경에서 useState의 값에 따라 button disabled 활성화/비활성화 하기 (0) | 2023.08.21 |