728x90
onClick 함수란?
사용자가 요소를 클릭했을 때 발생하는 이벤트입니다.
오류 발생 상황
- 컴포넌트가 렌더링 될 때 db에 있는 모든 자료들이 삭제가 되는 상황입니다.
코드
function CommentList() {
const [comments, setComments] = useState(null);
const fetchComments = async () => {
const { data } = await axios.get("http://localhost:3001/comments");
setComments(data);
};
const onDeleteComments = (id) => {
dispatch(deleteComment(id));
axios.delete(`http://localhost:3001/comments/${id}`);)
};
useEffect(() => {
fetchComments();
}, []);
return (
<StCmtForm>
{comments?.map((comment) => (
<StCmtCard>
<div key={comment.id}>{comment.contents}</div>
<button
background="black"
color="white"
onClick={onDeleteComments(comment.id)}
>
삭제
</button>
</StCmtCard>
))}
</StCmtForm>
);
}
export default CommentList;
❌ 오류가 발생한 이유 - onClick = { 함수 ( ) }
위 코드와 같이 onClick = { onDeleteComment ( comment.id ) } onDeleteComment 함수를 바로 호출 시, 컴포넌트가 렌더링 될 때 함수 자체가 아닌 함수 호출 결과가 onClick에 적용이 됩니다.
그래서 버튼 클릭시가 아닌 렌더링 될 때 onDeleteComment 함수가 실행이 되고 onDeleteComment 함수로 인해 db에 있는 모든 자료들이 삭제가 되는 것입니다.
⭕ 해결 방법
1. 화살표 함수
- onClick = { ( ) => 함수 ( ) }
화살표 함수를 사용하여 정의해야 하는 컴포넌트 state에 함수들이 접근할 수 있습니다.
return(
<button onClick={() => onDeleteComments(comment.id)}>삭제</button>
);
2. 함수 자체를 전달
- onClick = { 함수 }
클릭이벤트가 발생했을 때만, 함수가 실행되도록 함.
return(
<button onClick={onDeleteComments}>삭제</button>
);
마치며...
진짜 한 끗 차이로... 나는 틀리지 않았다는 확신을 가지고... 몇 시간을 태웠다...
역시 잘못은 내가 한 거였어...
728x90
'Frontend > React' 카테고리의 다른 글
[React] Hooks : optimizing 성능 최적화(3) - useCallback (1) | 2022.12.26 |
---|---|
[React] Hooks : optimizing 성능 최적화(2) - useMemo (1) | 2022.12.22 |
[React] Hooks : optimizing 성능 최적화(1) - React.memo( ) (0) | 2022.12.20 |
[React] Redux(3) [Redux Toolkit] (0) | 2022.12.20 |
[React] React-Router-Dom (0) | 2022.12.15 |
댓글